v9.1.1
Menu

Number of Islands

mediumFREEGraphsBlind 75

Given a 2D grid of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and formed by connecting adjacent land cells horizontally/vertically.

Input: grid, a 2D list whose cells are the single-character strings '1' and '0' (the example shows each row as comma-separated values). Return the island count as an integer.

Example

Input
1,1,1,1,0
1,1,0,1,0
1,1,0,0,0
0,0,0,0,0
Output
1
Reasoning
  • grid has 44 rows and 55 columns; each cell is the character 1 (land) or 0 (water). Writing cell positions as (row, column) from (0,0)(0,0), the land cells are: all of row 0 except column 4, then (1,0),(1,1),(1,3)(1,0), (1,1), (1,3), then (2,0),(2,1)(2,0), (2,1) — 99 land cells in total. Row 3 is all water.
  • Two land cells belong to the same island when you can walk from one to the other through land, stepping only up, down, left or right.
  • The left block (0,0)(0,0)–(2,1)(2,1) is a solid 3×23 \times 2 patch of land, joined to (0,2)(0,2) and (0,3)(0,3) along row 0. The cell (1,3)(1,3) sits directly below (0,3)(0,3), so it is joined too, even though water at (1,2)(1,2) separates it from (1,1)(1,1).
  • Every one of the 99 land cells is reachable from every other, so there is exactly one island and the answer is 1.
  • Notice that diagonal contact does not count: a lone 1 touching another only at a corner is its own island. A grid with no 1 at all gives 00.

Constraints

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

Learn this in

More from Blind 75

solution.py

Test results

Sign in to run your code against the test cases.