☰ All problems

Number of Islands

MediumGraphDFSBFSMatrix

A sailing app plans routes through an archipelago using a gridded chart, grid, of m × n cells: '1' marks land and '0' marks open sea. Land cells that touch horizontally or vertically belong to the same island, while cells that only meet at a corner are not connected. Everything beyond the edge of the chart is sea.

Return the number of separate islands on the chart.

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

Explanation: An L-shaped island on the left, a one-cell island in the top-right corner, a two-cell island in row 2 and a one-cell island in the bottom row.

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

Explanation: The right-hand column joins the top and bottom rows into a single island.

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

Explanation: The four land cells only meet at corners, so each one is an island of its own.

Constraints

  • The chart has between 1 and 300 rows and between 1 and 300 columns.
  • Every cell is the character '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