Number of Islands - Matrix and Grid Traversal Pattern
Number of Islands in Java using the Matrix and Grid Traversal pattern: problem statement, approach, template, complexity, and interview tips.
Number of Islands
Problem Statement
Count the islands in a grid of '1' (land) and '0' (water).
Pattern: Matrix and Grid Traversal
Treat a 2D grid as a graph where each cell connects to its four (or eight) neighbours and traverse it with DFS or BFS.
Use this pattern when the input is a grid of cells and you count regions, fill areas, or find reachable cells.
Approach
- Define the direction array and the bounds check.
- Start a DFS or BFS from each unvisited cell of interest.
- Mark cells visited (or mutate the grid) to avoid revisiting.
Pattern Template (Java)
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
void dfs(int[][] grid, int r, int c) {
if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length) return;
// return if the cell is invalid or already visited, then mark it
for (int[] d : dirs) {
dfs(grid, r + d[0], c + d[1]);
}
}
Adapt this template to the exact rules of Number of Islands: decide what state you track, what condition moves the loop forward, and what the final answer is.
Complexity
O(rows x cols) time and space in the worst case.
Interview Tips
- Confirm whether you may modify the input grid.
- For border-based problems, start the search from the border cells.
- Start with a brute-force idea, state its complexity, then explain how the Matrix and Grid Traversal pattern improves it.
- Walk through a small example and at least one edge case (empty input, a single element, duplicates).
Related Problems
Continue Learning
Parent: DSA Interview Learning Path | Previous: Flood Fill | Next: Surrounded Regions
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.