200. Number of Islands
2021-01-23 本文已影响0人
jluemmmm
找出二维数组中连成1组成的部分的数量。
- 时间复杂度 O(MN)
- 空间复杂度O(MN)
dfs,对二维网格进行遍历,对其上下左右节点进行递归,将已经识别过的1处理成0,dfs最重要的是要找到退出条件,越过矩阵边界或元素本身为0
- Runtime: 80 ms, faster than 93.00%
- Memory Usage: 39.9 MB, less than 54.87%
/**
* @param {character[][]} grid
* @return {number}
*/
var numIslands = function(grid) {
let m = grid.length
let n = grid[0].length
let res = 0
if (m === 0 || n === 0) return res
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if(grid[i][j] === '1') {
res++
dfs(i, j, grid)
}
}
}
return res
};
var dfs = function(i, j, grid) {
if(grid[i][j] === '0') return
let m = grid.length
let n = grid[0].length
grid[i][j] = '0'
if (i - 1 >= 0 && grid[i - 1][j]) dfs(i - 1, j, grid)
if (i + 1 < m && grid[i + 1][j]) dfs(i + 1, j, grid)
if (j - 1 >= 0 && grid[i][j - 1]) dfs(i, j - 1, grid)
if (j + 1 < n && grid[i][j + 1]) dfs(i, j + 1, grid)
}