Number of Islands

MediumGraphs

You get a map as a grid of one-letter strings: "1" is land and "0" is water. An island is a group of land cells joined up, down, left or right (not diagonally), and everything outside the grid is water.

Return how many islands the map has. On this page a grid is written as an array of rows, top row first, so grid[r][c] is row r, column c.

Examples

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

The three cells top left, the three top right, the lone 1 in the middle and the one bottom right.

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

The middle column joins the top row to the bottom row, so it is all one island.

Constraints

  • 1 ≤ m, n ≤ 300 for a grid of m rows and n columns
  • Every cell is "0" or "1".

Stuck?

Hint 1

Scan the grid. Each land cell you reach that is not yet part of a counted island starts a new one.

Hint 2

When you start an island, flood it: DFS or BFS through every land cell joined to it, marking each as seen (or turning it to "0"), so the scan never counts it again.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur