当前位置:网站首页>[JS solution] leedcode 200 Number of islands

[JS solution] leedcode 200 Number of islands

2022-06-13 04:39:00 xiaozhangtxue

Subject requirements :

Here you are ‘1’( land ) and ‘0’( water ) A two-dimensional mesh of , Please calculate the number of islands in the grid .
Islands are always surrounded by water , And each island can only be combined by horizontal direction / Or a vertical connection between adjacent lands .
Besides , You can assume that all four sides of the mesh are surrounded by water .

Example 1:

Input :grid = [
[“1”,“1”,“1”,“1”,“0”],
[“1”,“1”,“0”,“1”,“0”],
[“1”,“1”,“0”,“0”,“0”],
[“0”,“0”,“0”,“0”,“0”]
]
Output :1

Example 2:

Input :grid = [
[“1”,“1”,“0”,“0”,“0”],
[“1”,“1”,“0”,“0”,“0”],
[“0”,“0”,“1”,“0”,“0”],
[“0”,“0”,“0”,“1”,“1”]
]
Output :3

Solutions : Depth traversal

JS The code is as follows :

var numIslands = function (grid) {
    
  let res = 0
  let [m, n] = [grid.length, grid[0].length]
  if (m === 0 || n === 0) return 0
  //  Cyclic ergodic matrix 
  for (let i = 0; i < m; i++) {
    
    for (let j = 0; j < n; j++) {
    
      if (grid[i][j] === '1') {
    
        res++
        dfs(grid, i, j, m, n)
      }
    }
  }
  return res
}

//  Depth traversal dfs
function dfs(grid, i, j, m, n) {
    
  //console.log(grid)
  if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == '0') return
  grid[i][j] = '0'
  dfs(grid, i - 1, j, m, n)
  dfs(grid, i + 1, j, m, n)
  dfs(grid, i, j - 1, m, n)
  dfs(grid, i, j + 1, m, n)
}

Running results :

 Insert picture description here

原网站

版权声明
本文为[xiaozhangtxue]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206130436334414.html