200.岛屿数量(DFS M-岛屿系列)
/** * @param {character[][]} grid * @param {number} r * @param {number} c * @param {number} rSize * @param {number} cSize * @return */ function dfs(grid, r, c, rSize, cSize) { // 如果这个格子坐标超出或者不是岛屿,直接返回 if (!(0 <= r && r < rSize && 0 <= c && c < cSize) || grid[r][c] !== '1') { return } //标记已经遍历过的点 grid[r][c] = '2' // 访问上、下、左、右四个相邻结点 dfs(grid, r - 1, c, rSize, cSize) dfs(grid, r + 1, c, rSize, cSize) dfs(grid, r, c - 1, rSize, cSize) dfs(grid, r, c + 1, rSize, cSize) } /** * @param {character[][]} grid * @return {number} */ var numIslands = function (grid) { let rSize = grid.length let cSize = grid[0].length let res = 0 for (let r = 0; r < rSize; ++r) { for (let c = 0; c < cSize; ++c) { if (grid[r][c] === '1') { ++res dfs(grid, r, c, rSize, cSize) } } } return res }