可以直接使用深度优先遍历整个矩阵。大致的思路就是如果找到代表陆地的单元,则继续进行深度搜索,直到把所有相邻的陆地都找到,并且把它们的值标记为非陆地,防止重复搜索。
这样对于非陆地的单元,直接就可以结束。这样我们再从每一个单元进行深度搜索,这样就可以找到所有独立的岛屿了。
代码如下:
const numIslands = (grid) => {
const m = grid.length;
const n = grid[0].length;
let count = 0;
const dfs = (x, y) => {
// overflow values, return
if (x < 0 || y < 0 || x > m - 1 || y > n -1) {
return;
}
if (grid[x][y] === '1') {
// tag this unit
grid[x][y] = '0';
} else {
// stop the search if it is not land
return;
}
// search for all the nearby units
dfs(x + 1, y);
dfs(x, y + 1);
dfs(x - 1, y);
dfs(x, y - 1);
};
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === '1') {
// update the counter
count++;
// only start the search when it is land
dfs(i, j);
}
}
}
return count;
};