Java Graph Program · OT73
Count the Number of Islands in Java
Scan the grid. Every time you find land that has not been explored, you have found a new island; flood-fill it so it is never counted again.
Problem Statement
Given a grid of '1' (land) and '0' (water), count the islands. An island is a group of land cells connected horizontally or vertically.
Diagonal neighbours do not connect. The grid is surrounded by water.
Input/Output Examples
["11000", "11010", "00100", "00011"]Output4Explanation: a 2 × 2 block, two single cells and a pair.["000", "000"]Output0Explanation: no land.["111", "101", "111"]Output1Explanation: the ring is one connected island.Visual Explanation
| c0 | c1 | c2 | c3 | c4 | |
|---|---|---|---|---|---|
| r0 | A | A | . | . | . |
| r1 | A | A | . | B | . |
| r2 | . | . | C | . | . |
| r3 | . | . | . | D | D |
Each flood fill marks all cells of one island, so the outer scan starts exactly one fill per island and every cell is processed a constant number of times.
Approaches
Both approaches flood-fill each island once. One uses recursion and changes the grid; the other uses a queue and a visited array.
Approach 1: DFS Flood Fill (Recommended)
Idea: when a '1' is found, count it and recursively turn its whole island into '0'.
- Scan every cell.
- On land, increase the count and call
sink(). sink()sets the cell to'0'and recurses in four directions.
Time: O(rows × cols) · Space: O(rows × cols). Recursion depth in the worst case.
Approach 2: BFS With a Visited Array
Idea: explore each new island with a queue, marking cells in a separate boolean[][].
- Scan every cell.
- On unvisited land, increase the count and start a BFS from it.
- Add every unvisited land neighbour to the queue.
Time: O(rows × cols) · Space: O(rows × cols).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: DFS Flood Fill (Recommended)
Short and in place, but it modifies the input and can recurse deeply on large islands.
public class IslandsDfs {
// Each unvisited land cell starts a new island; the DFS sinks the whole island so it is counted once
static int countIslands(char[][] grid) {
int islands = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] == '1') {
islands++;
sink(grid, r, c);
}
}
}
return islands;
}
private static void sink(char[][] g, int r, int c) {
if (r < 0 || r >= g.length || c < 0 || 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);
}
public static void main(String[] args) {
String[][] grids = {
{"11000", "11010", "00100", "00011"},
{"000", "000"},
{"111", "101", "111"}};
for (String[] rows : grids) {
char[][] g = new char[rows.length][];
for (int i = 0; i < rows.length; i++) {
g[i] = rows[i].toCharArray();
}
System.out.println(String.join("/", rows) + " -> " + countIslands(g));
}
}
}
11000/11010/00100/00011 -> 4 000/000 -> 0 111/101/111 -> 1
Time complexity: O(rows × cols) · Space complexity: O(rows × cols).
Approach 2: BFS With a Visited Array
Leaves the input unchanged and cannot overflow the call stack.
import java.util.ArrayDeque;
import java.util.Deque;
public class IslandsBfs {
// Same counting idea, but each island is explored with a queue instead of recursion
static int countIslands(char[][] grid) {
int rows = grid.length, cols = grid[0].length, islands = 0;
boolean[][] seen = new boolean[rows][cols];
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == '1' && !seen[r][c]) {
islands++;
Deque<int[]> queue = new ArrayDeque<>();
queue.add(new int[] {r, c});
seen[r][c] = true;
while (!queue.isEmpty()) {
int[] cell = queue.poll();
for (int[] d : dirs) {
int nr = cell[0] + d[0], nc = cell[1] + d[1];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == '1' && !seen[nr][nc]) {
seen[nr][nc] = true;
queue.add(new int[] {nr, nc});
}
}
}
}
}
}
return islands;
}
public static void main(String[] args) {
String[][] grids = {
{"11000", "11010", "00100", "00011"},
{"000", "000"},
{"111", "101", "111"}};
for (String[] rows : grids) {
char[][] g = new char[rows.length][];
for (int i = 0; i < rows.length; i++) {
g[i] = rows[i].toCharArray();
}
System.out.println(String.join("/", rows) + " -> " + countIslands(g));
}
}
}
11000/11010/00100/00011 -> 4 000/000 -> 0 111/101/111 -> 1
Time complexity: O(rows × cols) · Space complexity: O(rows × cols).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| DFS Flood Fill | O(rows × cols) | O(rows × cols) |
| BFS With a Visited Array | O(rows × cols) | O(rows × cols) |
Here rows × cols is the grid size. Every cell is visited by the scan and at most once by a flood fill.
Interview Tips and Recommended Approach
- Ask whether the grid may be modified. If not, use a visited array.
- Clarify connectivity. With diagonals, the example has 3 islands instead of 4.
- Mention union-find for grids that receive new land cells over time.
- Use BFS for huge islands to avoid
StackOverflowError.
Recommended Approach: DFS Flood Fill
Why: it is the shortest correct solution and shows the flood-fill pattern used in many grid problems.