56. Number of Islands
grid is a map of "1" (land) and "0" (water). An island is a group of land cells connected horizontally or vertically. Count the islands.
Example 1
Input:
grid = [["1","1","0","0"],["1","0","0","1"],["0","0","1","1"]]Output:
2Example 2
Input:
grid = [["0"]]Output:
0Hint 1
Every unvisited land cell you meet starts a new island.
Hint 2
Flood-fill (DFS or BFS) the whole island so you never count it again.
Approach 1: DFS / BFS flood fill
Scan the grid; flood each new island.
⏱ Time O(m · n)💾 Space O(m · n)
Approach 2: Union-Find ✅
Union neighbouring land cells and count roots.
⏱ Time O(m · n · α)💾 Space O(m · n)
Reference solution for Union-Find (time O(m · n · α), space O(m · n)). Each solution passes every test in all four languages.
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])
def sink(r, c): # flood-fill one island
stack = [(r, c)]
grid[r][c] = '0'
while stack:
r, c = stack.pop()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == '1':
grid[nr][nc] = '0'
stack.append((nr, nc))
count = 0
for r in range(m):
for c in range(n):
if grid[r][c] == '1':
count += 1
sink(r, c)
return countclass Solution {
public int numIslands(char[][] grid) {
int count = 0;
for (int r = 0; r < grid.length; r++)
for (int c = 0; c < grid[0].length; c++)
if (grid[r][c] == '1') { count++; sink(grid, r, c); }
return count;
}
private void sink(char[][] g, int r, int c) { // DFS flood fill
if (r < 0 || c < 0 || r >= g.length || c >= g[0].length || g[r][c] != '1') return;
g[r][c] = '0';
sink(g, r + 1, c); sink(g, r - 1, c); sink(g, r, c + 1); sink(g, r, c - 1);
}
}class Solution {
void sink(vector<vector<char>>& g, int r, int c) { // DFS flood fill
if (r < 0 || c < 0 || r >= (int)g.size() || c >= (int)g[0].size() || g[r][c] != '1') return;
g[r][c] = '0';
sink(g, r + 1, c); sink(g, r - 1, c); sink(g, r, c + 1); sink(g, r, c - 1);
}
public:
int numIslands(vector<vector<char>>& grid) {
int count = 0;
for (int r = 0; r < (int)grid.size(); r++)
for (int c = 0; c < (int)grid[0].size(); c++)
if (grid[r][c] == '1') { count++; sink(grid, r, c); }
return count;
}
};function numIslands(grid) {
const m = grid.length, n = grid[0].length;
const sink = (r, c) => { // DFS flood fill
if (r < 0 || c < 0 || r >= m || c >= n || 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 count = 0;
for (let r = 0; r < m; r++)
for (let c = 0; c < n; c++)
if (grid[r][c] === '1') { count++; sink(r, c); }
return count;
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
Watch the core idea of this problem step by step. Change the input and press Visualize.
Explained in the lesson Graphs: BFS & DFS.
Run your code to see results here.