200. Number of Islands

Given an m x n 2d grid map of '1's (land) and '0's (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all 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

Constraints:

  • m == grid.length
  • n == gridi.length
  • 1 <= m, n <= 300
  • gridi is '0' or '1'.

Analyze

  • floodfill 算法。
/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function(grid) {
  const result = []
  const used = []
  for (let m = 0; m < grid.length; m++) {
    for (let n = 0; n < grid[m].length; n++) {
      if (used.indexOf(`${m},${n}`) === -1 && grid[m][n] === '1') {
        result.push(used)
        backTrace(grid, m, n, result, used)
      }
    }
  }
  return result.length
};

var backTrace = function(grid, m, n, result, used) {
  const direction = [[1, 0], [0, 1], [-1, 0], [0, -1]]
  for (let i = 0; i < direction.length; i++) {
    const use = used.indexOf(`${m + direction[i][0]},${n + direction[i][1]}`) > -1
    if (!use && grid[m + direction[i][0]] && grid[m + direction[i][0]][n + direction[i][1]] === '1') {
      used.push(`${m + direction[i][0]},${n + direction[i][1]}`)
      backTrace(grid, m + direction[i][0], n + direction[i][1], result, used)
    }
  }
}

Sister Title

130、200