Number of Islands

Medium

Topics
GraphDFSBFSUnion FindMatrix

Given an m x n grid of '1' (land) and '0' (water), return the number of islands. An island is surrounded by water and formed by connecting adjacent land cells horizontally or vertically.

Example 1

01111011101021100030000001234
Each shaded blob is one island: a maximal group of 1s joined horizontally or vertically (never diagonally). The shades alternate only so that neighbouring islands do not read as one. Counting the blobs gives the answer, 1.
2D grid — one row per line.
Input:  grid = ["11110","11010","11000","00000"]
Output: 1

Example 2

01100011100020010030001101234
Input:  grid = ["11000","11000","00100","00011"]
Output: 3

Constraints

  • 1 <= m, n <= 300
  • grid[i][j] is '0' or '1'.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Each island is a connected component of land cells. Walk the grid; every time you hit an unvisited land cell you have found a new island, so you flood-fill (sink) the whole component before continuing.

Approach

  1. Scan every cell.
  2. When you find a '1', increment the count and run DFS/BFS to turn all connected land into water so it is not counted again.
  3. The flood fill visits the 4 orthogonal neighbours.

Dry Run

grid  1 1 1 1 0
      1 1 0 1 0
      1 1 0 0 0
      0 0 0 0 0
The outer scan finds (0,0) still land, so that is island #1, and the flood fill
sinks the whole component before the scan moves on. The recursion order here is a
single chain, 9 frames deep for 9 cells:
  (0,0)
    (1,0)
      (2,0)
        (2,1)
          (1,1)
            (0,1)
              (0,2)
                (0,3)
                  (1,3)
grid afterwards  0 0 0 0 0
                 0 0 0 0 0
                 0 0 0 0 0
                 0 0 0 0 0
The scan continues over the remaining cells and finds nothing but water.
answer 1
Sinking on the way IN is what makes this correct and linear. The cell is set to
'0' before its neighbours are visited, so a neighbour looking back at it sees
water and stops; without that the two cells would call each other forever. It is
also why no separate visited set is needed -- the grid is the visited set.
Note the depth. Because the fill walks one cell per frame, a single component of
k cells costs k stack frames. With the problem's own limit of 300 x 300 that is
90000 frames for an all-land grid, and this page raises Python's recursion limit
to 100000 so the tests can run. Lift the Solution class on its own, with the
default limit of 1000, and a 32 x 32 all-land grid already raises RecursionError
while 30 x 30 still passes. The iterative version pushes onto an explicit stack
and sinks on push rather than on pop.

Complexity

  • Time — O(m*n): each cell is visited a constant number of times.
  • Space — O(m*n): recursion/queue depth in the worst case of one giant island.

Common Pitfalls

  • Mark cells visited (sink them) as you go, or you will count the same island many times.
  • The recursive flood fill costs one stack frame per cell, so a single component of k cells is k frames deep. At the stated limit of 300 x 300 that is 90000 frames for an all-land grid. This page raises Python's recursion limit so the tests can run; with the default limit of 1000, a 32 x 32 all-land grid already raises RecursionError while 30 x 30 still passes. Say so, and offer the explicit-stack version that sinks on push.

Full Solution — all languages

class Solution:
    def numIslands(self, grid):
        R,C=len(grid),len(grid[0])
        def sink(r,c):
            if r<0 or r>=R or c<0 or c>=C or grid[r][c]!='1': return
            grid[r][c]='0'
            sink(r+1,c);sink(r-1,c);sink(r,c+1);sink(r,c-1)
        cnt=0
        for r in range(R):
            for c in range(C):
                if grid[r][c]=='1':
                    cnt+=1; sink(r,c)
        return cnt
SensAI
Beta
Tap the mic to stop voice mode