Number of Islands (LeetCode 200): Solution and Explanation
You get a 2D grid of "1" for land and "0" for water. Land cells connect to their horizontal and vertical neighbors, and each connected group of land is one island. Count how many islands the grid contains.
Watch it run step by step
Try your own input and write the code →Intuition
Treat the grid as a graph. Every land cell is a node, and two land cells share an edge when they are next to each other horizontally or vertically. An island is then exactly a connected component, so the question becomes how many connected components the land graph has.
Counting components follows a standard pattern. Scan the cells in any order. When you reach a land cell that no earlier search has claimed, you have discovered a new island, so increment the count. Then explore everything reachable from that cell and mark it all as visited, so none of those cells can start another count later. By the end of the scan, every island has been counted exactly once, at its first cell in scan order.
The exploration itself is a flood fill, and BFS is a good fit. Put the starting cell in a queue, and repeatedly pop a cell and push any in-bounds, unvisited land neighbors. The important detail is to mark a cell visited when you push it, not when you pop it. Otherwise the same cell can be pushed several times by different neighbors before it is processed, which wastes time and memory on large islands.
Approach: BFS flood fill with a visited set
- Return 0 for an empty grid. Otherwise record
rowsandcols, create an emptyvisitset and setislands = 0. - Scan every cell. When a cell is "1" and not in
visit, it begins a new island, so runbfs(r, c)and incrementislands. - In
bfs, add the start cell tovisitand to a deque. - Pop a cell and check its four neighbors using the direction list.
- For each neighbor that is inside the grid, holds "1" and is not yet visited, append it to the queue and add it to
visitright away. - When the queue empties, the whole island is marked. After the scan ends, return
islands.
Step-by-step example
grid = [["1","1","0"],["0","1","0"],["0","0","1"]]
- The scan starts at (0,0), which is unvisited land, so BFS begins there.
- Popping (0,0): below is water, above is out of bounds, and right is (0,1), which is land, so it is queued and marked.
- Popping (0,1): below is (1,1), which is land, so it is queued and marked. Its other neighbors are water or already visited.
- Popping (1,1) finds only water and visited cells. The queue is empty, so
islandsbecomes 1. - The scan passes (0,1) and (1,1) because they are already in
visit. At (2,2) it finds unvisited land, runs a BFS that marks only that cell, andislandsbecomes 2. - The final answer is 2.
Code: Python, Java, C++
1class Solution:
2 def numIslands(self, grid: List[List[str]]) -> int:
3 if not grid:
4 return 0
5
6 rows, cols = len(grid), len(grid[0])
7 visit = set()
8 islands = 0
9
10 def bfs(r, c):
11 q = collections.deque()
12 visit.add((r, c))
13 q.append((r, c))
14 while q:
15 row, col = q.popleft()
16 directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
17 for dr, dc in directions:
18 r, c = row + dr, col + dc
19 if (r in range(rows) and
20 c in range(cols) and
21 grid[r][c] == "1" and
22 (r, c) not in visit):
23 q.append((r, c))
24 visit.add((r, c))
25
26 for r in range(rows):
27 for c in range(cols):
28 if grid[r][c] == "1" and (r, c) not in visit:
29 bfs(r, c)
30 islands += 1
31 return islands1class Solution {
2 public int numIslands(char[][] grid) {
3 if (grid == null || grid.length == 0) return 0;
4 int rows = grid.length, cols = grid[0].length;
5 int islands = 0;
6
7 for (int r = 0; r < rows; r++) {
8 for (int c = 0; c < cols; c++) {
9 if (grid[r][c] == '1') {
10 bfs(grid, r, c);
11 islands++;
12 }
13 }
14 }
15 return islands;
16 }
17
18 private void bfs(char[][] grid, int r, int c) {
19 Queue<int[]> q = new LinkedList<>();
20 q.add(new int[]{r, c});
21 grid[r][c] = '0'; // Mark visited
22
23 while (!q.isEmpty()) {
24 int[] curr = q.poll();
25 int row = curr[0], col = curr[1];
26 int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
27
28 for (int[] d : dirs) {
29 int nr = row + d[0], nc = col + d[1];
30 if (nr >= 0 && nr < grid.length && nc >= 0 && nc < grid[0].length &&
31 grid[nr][nc] == '1') {
32 q.add(new int[]{nr, nc});
33 grid[nr][nc] = '0';
34 }
35 }
36 }
37 }
38}1class Solution {
2public:
3 int numIslands(vector<vector<char>>& grid) {
4 if (grid.empty()) return 0;
5 int rows = grid.size(), cols = grid[0].size();
6 int islands = 0;
7
8 for (int r = 0; r < rows; r++) {
9 for (int c = 0; c < cols; c++) {
10 if (grid[r][c] == '1') {
11 bfs(grid, r, c);
12 islands++;
13 }
14 }
15 }
16 return islands;
17 }
18
19 void bfs(vector<vector<char>>& grid, int r, int c) {
20 queue<pair<int, int>> q;
21 q.push({r, c});
22 grid[r][c] = '0';
23
24 while (!q.empty()) {
25 auto [row, col] = q.front(); q.pop();
26 vector<pair<int, int>> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
27
28 for (auto [dr, dc] : dirs) {
29 int nr = row + dr, nc = col + dc;
30 if (nr >= 0 && nr < grid.size() && nc >= 0 && nc < grid[0].size() &&
31 grid[nr][nc] == '1') {
32 q.push({nr, nc});
33 grid[nr][nc] = '0';
34 }
35 }
36 }
37 }
38};Time and space complexity
O(m × n)
The outer scan touches every cell once, and each land cell enters a BFS queue exactly once, where it checks four neighbors. The total work is proportional to the number of cells.
O(m × n)
The visit set can hold every cell when the grid is all land, and the BFS queue can hold up to O(min(m, n)) cells along the frontier.
Other approaches
DFS flood fill that sinks land (time O(m × n), space O(m × n))
Recursively visit neighbors and overwrite each visited "1" with "0", which removes the need for a visited set. It is shorter but mutates the input and can hit recursion depth limits on large islands.
Union-Find (time O(m × n × α(m × n)), space O(m × n))
Give every land cell a parent, union each land cell with its land neighbors to the right and below, and count how many unions succeed. The island count is the number of land cells minus the successful unions. It shines when land is added over time, as in the follow-up problem.
Common mistakes
- Marking a cell visited when it is popped instead of when it is pushed, which lets the same cell enter the queue many times.
- Comparing grid cells to the integer 1 instead of the string "1", which makes every cell look like water.
- Counting diagonal neighbors as connected. Only up, down, left and right count.
- Incrementing the counter for every land cell rather than only when a new BFS starts.
Frequently asked questions
BFS or DFS for Number of Islands?
Both are O(m × n) and give the same count. BFS avoids recursion depth problems on huge islands, while DFS is shorter to write. Pick whichever you can code correctly quickly.
Why is the time complexity O(m × n)?
Every cell is visited once by the outer scan, and every land cell is processed once by a flood fill that checks four neighbors. That is a constant amount of work per cell.
Can you solve Number of Islands without extra space?
If you are allowed to modify the grid, overwrite visited land with "0" instead of using a set. The recursion stack or BFS queue still uses memory, so it is not strictly constant space.
When would you use Union-Find instead?
Union-Find is useful when land cells are added one at a time and you need the island count after each addition. Each update then costs nearly constant time instead of a new full scan.