Video in progress
How do you count the islands on a map made of 0s and 1s?
I walk through the grid. When I find a 1 I haven't seen yet, I increment the counter and "sink" the whole island with DFS or BFS, marking it as seen. Each cell is visited once, so it's O(rows·cols).
📖 Answer
static int islands(char[][] g) {
int count = 0;
for (int i = 0; i < g.length; i++) {
for (int j = 0; j < g[0].length; j++) {
if (g[i][j] == '1') {
count++;
sink(g, i, j);
}
}
}
return count;
}
static void sink(char[][] g, int i, int j) {
if (i < 0 || j < 0 || i >= g.length || j >= g[0].length || g[i][j] != '1') return;
g[i][j] = '0';
sink(g, i + 1, j);
sink(g, i - 1, j);
sink(g, i, j + 1);
sink(g, i, j - 1);
}
The interviewer often asks two things.
First: is it allowed to modify the input array? If not, you allocate a boolean[][] visited. In practice, corrupting the caller's data is an unpleasant surprise, so I usually work with a copy or with visited.
Second: what happens if a 2000×2000 grid is entirely 1s? The recursion depth reaches millions and the stack overflows. Then you write sink as BFS with an ArrayDeque: same logic, a queue instead of the stack.
Variants of this problem: the area of the largest island, the perimeter of islands, lakes that "don't reach the open sea".
Sign up to mark studied questions and save your progress.