This is a recursive approach using DFS to counting the number of islands. However, I would like to improve performance, while keeping the code clean concise and readable. Better yet can this be solved using bitwise operations?
var numIslands = function(grid) {
const search = (row, col, grid) => {
if (row < 0 || col < 0 ||
row > grid.length - 1 || col > grid[row].length - 1 ||
grid[row][col] === '0') {
return;
}
grid[row][col] = '0';
search(row - 1, col, grid);
search(row, col - 1, grid);
search(row + 1, col, grid);
search(row, col + 1, grid);
}
let count = 0;
grid.forEach((row, index) => {
row.forEach((value, i) => {
if (value === "1") {
search(index, i, grid)
count++
}
})
})
return count
}
console.log(numIslands([
["1", "1", "1"],
["1", "1", "0"],
["1", "1", "1"],
["0", "1", "0"],
["1", "1", "1"]
]))
console.log(numIslands([
["1", "1", "1"],
["0", "0", "0"],
["1", "1", "1"],
["0", "0", "0"],
["1", "1", "1"]
]))
console.log
you should rather write real unit tests. The main point is that these unit tests not only contain the input data but also the expected output data. Seeing that the expected output for the first test case is 1, it would be obvious that you define an island as a continuous region of 1's. Your question is missing this very central definition. \$\endgroup\$