☰ All problems

62. Number of Islands

MediumGraphDFSBFSMatrix

You are given a map grid of m × n cells, where '1' is land and '0' is water.

An island is a group of land cells connected horizontally or vertically (diagonal neighbours do not count). Everything outside the grid is water. Return the number of islands.

Example 1
Input: grid = [["1","1","0","0","1"],["1","0","0","1","1"],["0","0","1","0","0"],["1","0","0","0","1"]]
Output: 5

Explanation: The top-left L shape, the top-right L shape, the single cell in the middle and the two bottom corners.

Example 2
Input: grid = [["1","1","1"],["1","0","1"],["1","1","1"]]
Output: 1

Explanation: A ring of land is still one island; the water in the middle does not split it.

Example 3
Input: grid = [["1","0"],["0","1"]]
Output: 2

Explanation: The two cells only touch diagonally.

Constraints

  • 1 <= m, n <= 300
  • grid[i][j] is '0' or '1'

Follow-up: Land is added one cell at a time and you must report the island count after every addition. Which data structure makes that fast?

💡 Hint 1

Scan every cell. Each time you find land that you have not visited yet, you have found a new island.

💡 Hint 2

From that cell, flood-fill (DFS or BFS) to every connected land cell and mark them visited so they are not counted again.

💡 Hint 3

You can mark cells by overwriting them with '0', or keep a separate visited matrix if the input must not change.

/**
 * @param {character[][]} grid
 * @return {number}
 */
function numIslands(grid) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc