Number of Islands
Medium
Topics
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
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
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
- Scan every cell.
- 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.
- 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
RecursionErrorwhile 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 cntimport java.util.*;
class Solution {
public int numIslands(char[][] grid) {
int R=grid.length,C=grid[0].length,cnt=0;
for(int r=0;r<R;r++)for(int c=0;c<C;c++)if(grid[r][c]=='1') {
cnt++;
sink(grid,r,c);
}
return cnt;
}
void sink(char[][] grid,int r,int c) {
int R=grid.length,C=grid[0].length;
if(r<0||r>=R||c<0||c>=C||grid[r][c]!='1')return;
grid[r][c]='0';
sink(grid,r+1,c);
sink(grid,r-1,c);
sink(grid,r,c+1);
sink(grid,r,c-1);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int numIslands(vector<vector<char>>& grid) {
int R=grid.size(),C=grid[0].size(),cnt=0;
function<void(int,int)> sink=[&](int r,int c) {
if(r<0||r>=R||c<0||c>=C||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);
};
for(int r=0;r<R;r++)for(int c=0;c<C;c++)if(grid[r][c]=='1') {
cnt++;
sink(r,c);
}
return cnt;
}
};/**
* @param {character[][]} grid
* @return {number}
*/ var numIslands = function(grid) {
const R=grid.length,C=grid[0].length;
function sink(r,c) {
if(r<0||r>=R||c<0||c>=C||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);
}
let cnt=0;
for(let r=0;r<R;r++)for(let c=0;c<C;c++)if(grid[r][c]==='1') {
cnt++;
sink(r,c);
}
return cnt;
};