题目地址: 链接
思路: 如果当前为陆地且未被访问过,则对当前路径进行 dfs(同时标记为访问过),最后统计进入最外层 dfs 的次数
js
/**
* @param {character[][]} grid
* @return {number}
*/
var numIslands = function(grid) {
const dfs = (x, y) => {
isVit[x][y] = true;
for(let i = 0; i < 4; i ++) {
let [nx, ny] = [x + dx[i], y + dy[i]];
if(0 <= nx && nx < n && 0 <= ny && ny < m && !isVit[nx][ny] && grid[x][y] == '1') {
dfs(nx, ny);
}
}
}
let [n, m] = [grid.length, grid[0].length];
let isVit = Array.from({length: n}, ()=>new Array(m).fill(false));
let ans = 0;
const dx = [0, 1, 0, -1];
const dy = [1, 0, -1, 0];
for(let i = 0; i < n; i ++) {
for(let j = 0; j < m; j ++) {
if(!isVit[i][j] && grid[i][j] == '1') {
dfs(i, j);
ans ++;
}
}
}
return ans;
};