Q19: How do you solve Number of Islands using Graph Search (DFS / BFS)?
Iterate through the 2D grid matrix. When encountering '1' (land), increment island count and trigger DFS/BFS to sink connected land cells by mutating grid cells to '0' (or marking them visited). Repeat for all unvisited land cells.
DFS Number of Islands Solution
public class NumberOfIslands {
public static int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) return 0;
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++;
dfs(grid, r, c);
}
}
}
return count;
}
private static void dfs(char[][] grid, int r, int c) {
if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length || grid[r][c] == '0') {
return;
}
grid[r][c] = '0'; // Sink land
dfs(grid, r + 1, c);
dfs(grid, r - 1, c);
dfs(grid, r, c + 1);
dfs(grid, r, c - 1);
}
}💡 Traverses and sinks adjacent land cells recursively when a new island is detected.
Key Takeaways
- 2D Grid Graph Traversal using DFS or BFS.
- In-place land sinking (
'1'$ o$'0') eliminates $O(m imes n)$ auxiliary visited array memory.
Knowledge Check
What is the time complexity of the Number of Islands graph traversal on an M x N grid?