Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Given a grid char[][] of '1' (land) and '0' (water), write Java code that counts islands of connected land cells (up, down, left, right). Explain whether you would use BFS or DFS and why.

We loop over every cell, and each time we find an unvisited '1' we count a new island and flood fill from it, marking every land cell connected to it up, down, left or right as visited. I would use BFS with an ArrayDeque<int[]>, because recursive DFS is shorter but can overflow the stack on a large grid that is mostly land. We mark cells by changing them to '0', or with a boolean[][] when the input must not change, check bounds before indexing, and the whole thing runs in O(rows * cols) time and O(rows * cols) space in the worst case.

Why this question is asked

Counting islands is the classic introduction to graph traversal on a grid, and the same pattern solves real tasks: finding connected regions in images, clusters of failing hosts in a rack map, or groups of linked records. Interviewers use it to check that we can see a grid as a graph, write a clean flood fill, and reason about which traversal is safe for large inputs. In this answer, we will see the grid as a graph, walk through the counting idea, write a BFS solution, compare it with recursive DFS, look at marking strategies and complexity, and answer the union-find follow-up.

1Seeing the Grid as a Graph

Each cell of the grid is a node. Two land cells are connected by an edge when they are next to each other horizontally or vertically; diagonal neighbours do not count in this problem. An island is then a connected component: a group of land cells where we can walk from any cell to any other through land neighbours.

So counting islands means counting connected components among the land cells. The standard way is to start a traversal from any land cell we have not seen yet, mark everything reachable from it, and count how many times we had to start a new traversal.

2The Counting Idea, Step by Step

We scan the grid row by row. When we meet a '1' that has not been visited, it must belong to an island we have not counted yet, because every cell of an already counted island was marked when we flood filled it. So we add one to the count and flood fill from this cell: visit it, then every land neighbour, then their land neighbours, and so on, marking each one. When the fill finishes, the whole island is marked, and the scan continues.

A 4 x 5 grid with 3 islands
RowCellsIsland found by the scan
01 1 0 0 0island 1 starts at (0,0), covers (0,0) (0,1) (1,0) (1,1)
11 1 0 0 0already marked by island 1
20 0 1 0 0island 2 starts at (2,2)
30 0 0 1 1island 3 starts at (3,3), covers (3,3) (3,4)
(2,2) and (3,3) touch only diagonally, so they are separate islands.

3Writing It With BFS

Breadth-first search, BFS, explores from the start cell outwards using a queue: take a cell from the front, add its unvisited land neighbours to the back. Here we store each cell as an int[] of row and column in an ArrayDeque.

Java
private static final int[] DR = {-1, 1, 0, 0};
private static final int[] DC = {0, 0, -1, 1};
static int countIslands(char[][] grid) {
if (grid == null || grid.length == 0) return 0;
int rows = grid.length, cols = grid[0].length, count = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == '1') {
count++;
flood(grid, r, c);
}
}
}
return count;
}
private static void flood(char[][] grid, int r0, int c0) {
Deque<int[]> queue = new ArrayDeque<>();
grid[r0][c0] = '0'; // mark when adding, not when removing
queue.add(new int[] {r0, c0});
while (!queue.isEmpty()) {
int[] cell = queue.poll();
for (int d = 0; d < 4; d++) {
int r = cell[0] + DR[d], c = cell[1] + DC[d];
if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length) continue; // bounds first
if (grid[r][c] != '1') continue;
grid[r][c] = '0';
queue.add(new int[] {r, c});
}
}
}
char[][] g = {
"11000".toCharArray(),
"11000".toCharArray(),
"00100".toCharArray(),
"00011".toCharArray()};
countIslands(g); // 3

Notice two details. The direction arrays DR and DC turn four nearly identical blocks of neighbour code into one loop. And we mark a cell as soon as we add it to the queue, not when we take it out. If we marked on removal, the same cell could be added several times by different neighbours before it is processed, wasting time and memory.

4BFS or DFS?

Depth-first search, DFS, explores one path as far as it goes before backing up. Written recursively, it is shorter than BFS: mark the cell, then call itself on the four neighbours. That is often how people first write this problem, and it is fine for small grids.

Java
private static void dfs(char[][] g, int r, int c) {
if (r < 0 || c < 0 || r >= g.length || c >= g[0].length || g[r][c] != '1') return;
g[r][c] = '0';
dfs(g, r + 1, c); dfs(g, r - 1, c); dfs(g, r, c + 1); dfs(g, r, c - 1);
}
// A 2,000 x 2,000 grid of all land: the recursion can go millions of calls deep
// -> java.lang.StackOverflowError

The problem is depth. On a grid that is mostly land, a recursive DFS can wind through every cell before it backs up, so its depth can approach rows * cols. A default thread stack holds only some tens of thousands of frames, so a 2,000 x 2,000 grid of land overflows it. BFS keeps its pending cells in a queue on the heap, so it has no such limit. We could also write DFS iteratively with an ArrayDeque used as a stack; the count is the same either way, since both visit every cell of the island. So I would choose BFS, or iterative DFS, for anything that might be large, and mention recursive DFS as the short version for small inputs.

5Marking Visited Cells and Complexity

Changing visited cells to '0' is the simplest way to mark them and uses no extra memory, but it destroys the input. If the caller still needs the grid, which is common in real code, we use a separate boolean[][] visited of the same size and check it alongside the cell value. That costs rows * cols bytes, about 4 MB for a 2,000 x 2,000 grid.

Every cell is examined once by the scan and at most once by a flood fill, and each examination checks four neighbours, so the time is O(rows * cols). The extra space in the worst case is also O(rows * cols): the visited array if we use one, and the BFS queue, which can hold a large share of the cells of one island at a time (for BFS its size is closer to the width of the frontier, but we quote the worst case).

6Follow-up questions

How would union-find solve the same problem?

Union-find, also called disjoint set union, keeps a parent array where each cell points towards a representative of its group. We start with each land cell as its own group and count = number of land cells. Then for each land cell we union it with its land neighbours to the right and below; every union that joins two different groups reduces the count by one. With path compression and union by rank, each operation is nearly O(1), so the total is about O(rows * cols). Union-find shines when land is added over time, the 'islands II' variant, because each new cell needs only a few unions instead of a fresh traversal.

What changes if diagonal cells count as connected?

Only the direction arrays: we use eight directions, adding the four diagonal offsets. In the example grid, (2,2) and (3,3) would then join, and the count would drop to 2.

How would you find the size of the largest island?

Count cells during each flood fill, incrementing a counter every time a cell is added to the queue, and keep the maximum across fills. The complexity stays O(rows * cols).

7Conclusion

In this answer, we treated the grid as a graph of land cells joined to their four neighbours and counted islands as connected components: scan every cell, and on each unvisited '1' count an island and flood fill it. BFS with an ArrayDeque<int[]> avoids the stack overflow that recursive DFS risks on large, mostly land grids. We marked cells by setting them to '0', or used a boolean[][] when the input must be kept, checked bounds before indexing with direction arrays, and the solution runs in O(rows * cols) time and worst-case space. Union-find gives the same count and suits grids that change over time.

What to say in the interviewAbout 90 seconds aloud

Open with

I treat each land cell as a node connected to its up, down, left and right land neighbours, so an island is a connected component. I scan the grid, and whenever I find a '1' that has not been visited, I increment the count and flood fill from it to mark the whole island, so I never count it again.

Then, if they want more

For the fill I would use BFS with an ArrayDeque of int arrays holding row and column: mark the start cell, add it, then repeatedly poll a cell and add each in-bounds unvisited land neighbour, marking it as I add it so nothing is queued twice.

I use two small direction arrays to keep the neighbour code to one loop, and I check bounds before indexing. Recursive DFS is shorter, but on a large grid that is mostly land the recursion can go as deep as the number of cells and overflow the thread stack, so BFS or an iterative DFS is safer.

To mark cells I can overwrite them with '0', or use a boolean visited array if the caller needs the grid unchanged. Time is O(rows times cols), since every cell is visited a constant number of times, and worst-case extra space is also O(rows times cols). Union-find is an alternative, especially if cells turn into land over time.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Given a grid char[][] of '1' (land) and '0' (water), write Java code that counts islands...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/a8e25eb572/