Skip to content

Latest commit

 

History

History
47 lines (42 loc) · 947 Bytes

200.number-of-islands.md

File metadata and controls

47 lines (42 loc) · 947 Bytes

岛屿数量

题目

思路

对整个数组进行遍历, 遇到岛屿则将岛屿以及周边连在一起的全部设置为空. 即可得到最终的大陆数量

/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function(grid) {
  let num = 0
  const xlength = grid.length
  if (xlength === 0) {
    return num
  }
  const ylength = grid[0].length
  if (ylength === 0) {
    return num
  }
  function remove (x, y) {
    if (x < 0 || y < 0 || x > xlength - 1 || y > ylength - 1) {
      return false
    }
    if (grid[x][y] === '1') {
      grid[x][y] = '0'
      remove(x - 1, y)
      remove(x + 1, y)
      remove(x, y - 1)
      remove(x, y + 1)
    }
  }
  for (let i = 0; i < xlength; i++) {
    for (let j = 0; j < ylength; j++) {
      if (grid[i][j] === '1') {
        num = num + 1
        remove(i, j)
      }
    }
  }

  return num
};