Quick revision
The short answer
Counting islands is graph traversal in disguise: each land cell is a node joined to the land beside it, and each island is one connected group. We scan the grid, and every time we meet land we have not seen, we count one island and flood fill all of it with a stack so it is never counted again. Every cell is handled a constant number of times, so it takes O(rows x cols) time and space.
The solution
What it costs
| Approach | Time | Extra space | Correct? |
|---|---|---|---|
| Count top left corners | O(r c) | O(1) | no, a U or (1,3) fools it |
| Relabel until nothing changes | O((r c) squared) | O(r c) | yes |
| Scan and flood fill with a stack | O(r c) | O(r c) | yes |
| Union-find over land cells | O(r c), nearly | O(r c) | yes |
What to remember
We counted islands the way we would with a highlighter on a map. Judging cells one at a time fails, because joining belongs to the whole group, and relabelling until nothing changes works but sweeps the grid again and again. Seeing the grid as a graph, we scan for unseen land, count it as a new island, and flood fill it with a stack, marking cells as we push them, for O(r c) time and space. The clue to remember is counting groups of joined cells: that is connected components, one traversal from every unvisited node.
1What an island is, on a map drawn on squared paper
Picture a map of a small sea drawn on squared paper, each square sea or land, and a highlighter in your hand. To count the islands, you would find land you have not coloured, say that this is a new island, colour all the land joined to it, and look for the next uncoloured land. The number of times you said a new island is the answer. Keep this highlighter in mind, because our program does exactly this.
In the question the map is a grid, a table of numbers with rows and columns. Each square is called a cell, and we name it by row and column, both counted from 0, so (1,3) is row 1, column 3. A 1 is land and a 0 is water. Two land cells belong to the same island when they touch along a side, one directly above, below, left or right of the other. These four cells are called the neighbours of a cell; touching at a corner does not count. The job is smaller than it looks: no shapes or sizes, only how many groups, and each cell has at most four neighbours.
We will keep one example throughout, the rows 1 1 0 0 1, then 1 0 0 1 1, then 0 0 1 0 0, then 1 0 1 1 0, and do it by hand. (0,0) is land, and so are its right neighbour (0,1) and the cell below it, (1,0); nothing else touches these three, so they are island 1. The top right corner (0,4), the cell below it (1,4), and (1,3) to the left of that form island 2. In the middle, (2,2) touches (3,2), which touches (3,3), and that is island 3. Finally (3,0) has water above it and to its right, so it is an island of one cell. The answer is 4.
1 is land and 0 is water. Land cells are marked; the panel lists which land cells belong together.
- island 1
- (0,0) (0,1) (1,0)
- island 2
- (0,4) (1,4) (1,3)
- island 3
- (2,2) (3,2) (3,3)
- island 4
- (3,0)
- answer
- 4
1Ten land cells make four islands, because cells only join when they touch along a side. The panel lists each island's cells as (row, column).
What to assume
- Do diagonal neighbours count?
- We assume not.
- May we change the grid?
- No.
- Is everything outside the grid water?
- Yes.
- Can the grid be empty?
- Yes, and the answer is then 0.
- How large can it be?
- Perhaps a million cells.
Notice one thing in the picture. (1,3) has water above it and on its left, yet it belongs to island 2, because it touches (1,4). Whether a cell starts a new island depends on its whole group, not on the cell alone, and that will matter in a moment.
A careful candidate asks a few questions first. Do diagonal neighbours count? We assume not. May we change the grid? No, so we keep our own record of the cells we have seen. Is everything outside the grid water? Yes. Can the grid be empty? Yes, and the answer is then 0. How large can it be? Perhaps a million cells, which will shape one decision later.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a graph hiding inside a grid
A beginner sees a grid of numbers and thinks of two loops over rows and columns. That is right as far as it goes, but a loop looking at one cell cannot tell which island it belongs to. The difficulty is the joining, and that is where the clues lie.
The first clue is the word connected, or in other versions joined or adjacent. It says that what matters is which cells touch which, and a question about things joined to other things is describing a graph. A graph is simply a set of dots with lines between some of them. The dots are called nodes, and in our map every land cell is a node.
The second clue is the rule for joining, up, down, left and right. Each such touch between two land cells is a line in our graph, called an edge. Nobody hands us a list of edges, because we can work them out from a cell's row and column whenever we need them. A graph computed as we go, instead of stored, is called an implicit graph, and grids are the most common one in interviews.
The third clue is the word count, attached to groups rather than cells. A group of nodes that can all reach each other along edges, and touches nothing else, is called a connected component, and an island is exactly that. Together the clues point to the pattern called graph traversal. To traverse a graph means to visit every node reachable from a starting node by walking along edges, each node once. The rule to carry to new problems is this: when a question asks you to count or measure groups of joined things, start a traversal from every node not yet visited, and count the traversals. Each traversal is one stroke of the highlighter.
Two other ideas look possible. Dynamic programming moves across the grid in one direction, but an island can curl back on itself, which one pass cannot see. Union-find, a structure that keeps groups and merges them quickly, does solve the problem and is better when land arrives one cell at a time, but for a fixed grid a traversal is simpler to write and to explain.
3The honest first attempts, corners and then relabelling
It is natural to look for a shortcut first, and worth trying one honestly. A tempting one is to count every land cell whose upper and left neighbours are both water, as if each island had exactly one top left corner. On our example that counts (0,0), (0,4), (1,3), (2,2) and (3,0), which is 5, one too many, because (1,3) is part of island 2. A U shaped island, 1 0 1 above 1 1 1, fails the same way, since both arms have such a corner. Cells cannot be judged one by one, because joining belongs to the whole group.
So we need a way for joined cells to agree with each other. A brute force that works is relabelling. Give every land cell its own label, a different number for each, and leave water as 0. Sweep the whole grid, and at every land cell replace its label with the smallest label among itself and its land neighbours. Repeat until a whole sweep changes nothing. Labels only travel between cells that touch, so two islands never share one, and when nothing changes, every cell agrees with its neighbours, so each island holds a single label. The answer is the number of different labels.
Each number is a land cell's label and 0 is water. Cells whose label changed in that sweep are marked as compared.
- sweep
- 0
- labels changed
- 0
- cells visited
- 0
1Before any sweep, every land cell holds its own label, its place in the grid counted from 1. Ten land cells, ten different labels.
- sweep
- 1
- labels changed
- 5
- cells visited
- 20
2Sweep 1 visits all 20 cells. Five labels change, each to a smaller label next door, so island 1 becomes all 1s and island 3 all 13s.
- sweep
- 2
- labels changed
- 1
- cells visited
- 40
3Sweep 2 visits all 20 cells again to change one label: (1,3) finally takes 5 from its right neighbour. Everything else had already settled.
- sweep
- 3
- labels changed
- 0
- cells visited
- 60
4Sweep 3 visits all 20 cells and changes nothing, so the loop stops. Four distinct labels are left, 1, 5, 13 and 16, so there are 4 islands.
On our example each sweep visits all 20 cells, and three sweeps make 60 visits, though sweep 2 changed one label and sweep 3 none.
On a bigger map it gets much worse. A label moves only a short way in one sweep, so a long island that winds back and forth, like a snake, can need about as many sweeps as it has cells. With r rows and c columns, a sweep costs about r times c steps and we may need about r times c sweeps, so the time grows like (r c) squared, a million million steps for a thousand by a thousand grid. The waste is that every sweep revisits cells and islands that settled long ago, only to push a label a little further. That suggests the question to ask. When we first stand on a piece of land, why not follow its connections at once, instead of waiting for sweeps to carry the news?
4Getting to the scan and flood fill, one observation at a time
The first observation is the highlighter. If we follow connections at once, one visit per island is enough. We scan the grid row by row, and when the scan meets land we have not seen, it must belong to an island not yet counted, so we add one to the count. Then, before the scan moves on, we visit every land cell joined to it and mark each as seen. This spreading is called a flood fill, because it moves the way water fills a basin.
The second observation is about memory. From (0,0) there are two new land cells, (1,0) and (0,1), but we can stand on only one at a time, so the other must wait somewhere. We keep waiting cells in a stack, which works like a pile of plates: we put a cell on top, called a push, and take the top cell off, called a pop. The flood fill is then a short loop. While the stack is not empty, pop a cell and look at its four neighbours, and each one that is inside the grid, is land and is not yet seen gets marked and pushed. When the stack is empty, the island is marked.
The third observation is the record itself, a boolean array seen, one true or false per cell. It stops the scan from counting an island twice and the fill from bouncing between two neighbours forever.
A beginner often asks whether to mark a cell when we push it or when we pop it. Let us try marking on pop with a two by two block of land. Popping the top left, we push the bottom left and then the top right, neither marked yet. Popping the top right, we push the bottom right. Popping the bottom right, we see the bottom left, still waiting on the stack and still unmarked, so we push it a second time. The count stays right, but on a large island the stack fills with copies. Marking on push means every cell enters the stack at most once.
Why not recursion, which looks shorter? Every unfinished recursive call waits on Java's call stack, a small region of memory, and an island of a million cells could need a million waiting calls and end in a StackOverflowError. Our own ArrayDeque lives in ordinary memory and grows as needed.
Why is the count right? When the scan reaches an island's first cell in reading order, none of its cells has been seen, because fills never cross water, so it is counted then, and its fill marks all its cells so the scan skips them later. One slip tempts everyone: reading grid[nr][nc] before checking that nr and nc are inside the grid. Looking up from the top row gives row -1 and an ArrayIndexOutOfBoundsException, so the bounds check always comes first.
5Watching the scan and the flood fill on the example
The picture plays the program on our map, scanning in reading order. The cell being handled is marked as now, a cell seen and waiting on the stack is marked as compared, and a cell seen and popped is done. The panel shows the island count, the stack with its top first, and where the scan has reached.
Watch two things. A cell is marked the moment it is pushed, before it is ever popped. And the count goes up only when the scan itself finds unseen land, never during a fill.
Marked as now: the cell being handled. Compared: seen and waiting on the stack. Done: seen and finished. Water is never marked. The stack is listed top first.
- islands
- 0
- stack
- empty
- scan is at
- (0,0)
1The scan starts at the top left, (0,0). No island has been counted, the stack is empty and no cell is marked as seen.
- islands
- 1
- stack
- (0,0)
- scan is at
- (0,0)
2(0,0) is land and not yet seen, so it starts a new island. islands becomes 1, and (0,0) is marked seen and pushed on the stack.
- islands
- 1
- stack
- (0,1) (1,0)
- scan is at
- (0,0)
3We pop (0,0) and look down, up, right and left. Down is (1,0) and right is (0,1), both new land, so both are marked and pushed. (0,1) is on top.
- islands
- 1
- stack
- empty
- scan is at
- (0,0)
4We pop (0,1), then (1,0). Neither has a new land neighbour, so nothing is pushed. The stack is empty, and island 1 is completely marked.
- islands
- 2
- stack
- (0,4)
- scan is at
- (0,4)
5The scan moves on. (0,1) is land but already seen, so it is skipped and not counted again. At (0,4) we meet new land: islands becomes 2.
- islands
- 2
- stack
- (1,4)
- scan is at
- (0,4)
6Popping (0,4) finds one new land neighbour, (1,4) below it, which is marked and pushed.
- islands
- 2
- stack
- (1,3)
- scan is at
- (0,4)
7Popping (1,4) finds (1,3) on its left. The fill reaches (1,3) through (1,4), even though (1,3) has no land above it.
- islands
- 2
- stack
- empty
- scan is at
- (0,4)
8Popping (1,3) finds nothing new, and the stack is empty. Island 2, three cells, is marked.
- islands
- 3
- stack
- empty
- scan is at
- (2,2)
9The scan skips (1,0), (1,3) and (1,4), all seen, and finds (2,2). islands becomes 3, and the fill reaches (3,2) and then (3,3) before the stack empties.
- islands
- 4
- stack
- empty
- scan is at
- (3,0)
10At (3,0) the scan finds new land again, so islands becomes 4. Its fill pops (3,0), finds no land neighbour, and stops at once.
- islands
- 4
- stack
- empty
- scan is at
- (3,4)
11The scan skips (3,2) and (3,3), which are seen, and reaches the last cell. Every land cell was counted in exactly one fill, so the answer is 4.
Look again at the third frame. Popping (0,0) checks the neighbours in the order down, up, right, left, so (1,0) is pushed first and (0,1) second, and (0,1) ends up on top, because a stack hands back the most recent cell first.
The fifth frame shows why seen is needed. When the scan reaches (0,1), it is land, but it was marked during island 1's fill, so the scan skips it. Without that check the answer would be 10, one per land cell.
The seventh frame settles the corner shortcut. The fill reaches (1,3) from (1,4), so (1,3) is already seen when the scan arrives and is never taken for a new island. By the last frame the scan has started exactly four fills, so the answer is 4.
6The complete Java program
Here is the whole program. The four directions sit in a small array called STEPS, so looking at the neighbours is one short loop. main counts the islands of our example, of a grid with no land, and of a single land cell.
Let us read countIslands in the order it runs. The first line returns 0 for a grid with no rows. Then we create seen, which Java fills with false, and one stack that every fill reuses.
The two for loops are the scan. The first line inside uses continue to skip water and cells already seen. If we get past it, we stand on unseen land, so islands goes up by one, the cell is marked seen, and it is pushed to start its fill.
The while loop is the highlighter at work. It pops a cell and, for each of the four steps, works out the neighbour's row nr and column nc. The first check skips a neighbour outside the grid, and it comes first so we never read outside the array. The second skips water and seen cells. A neighbour that survives both is marked and then pushed. When the stack is empty the scan carries on where it stopped. grid is only read, never written, and main prints 4, then 0, then 1.
7How much it costs, and the cases at the edges
Let us count on the example first. The scan looked at all 20 cells once. The ten land cells were each pushed and popped once, and each popped cell checked four neighbours, 40 checks, against 60 cell visits for relabelling. For r rows and c columns, the scan costs r c steps and the fills a few steps per cell, because no cell is pushed twice, so the time is O(r c), growing in step with the number of cells. No method can do better, since every cell must be looked at once.
The seen array holds one boolean per cell, and on a grid of all land the stack can hold a large share of the cells at once, so the extra space is O(r c) as well.
| Approach | Time | Extra space | Correct? |
|---|---|---|---|
| Count top left corners | O(r c) | O(1) | no, a U or (1,3) fools it |
| Relabel until nothing changes | O((r c) squared) | O(r c) | yes |
| Scan and flood fill with a stack | O(r c) | O(r c) | yes |
| Union-find over land cells | O(r c), nearly | O(r c) | yes |
The edge cases need very little code. A grid with no rows returns 0 at once, and a grid of water never starts a fill, so main prints 0. A single land cell starts one fill that finds no neighbours, so the answer is 1. A grid of all land starts one fill, and the explicit stack lets it finish without overflowing. Land on the border needs nothing special, because the bounds check treats the outside as water.
We assume every row has the same length, since cols is read from row 0. If we may change the grid, we can turn each land cell to 0 as we push it and drop the seen array, which saves memory but spoils the caller's map.
8Follow-up questions
Could you use breadth first search instead of a stack?
Yes, and the answer is the same. Breadth first search replaces the stack with a queue, which works like a line at a counter: cells join at the back and leave from the front. The fill then spreads outward in rings from the starting cell instead of running down one path first. For counting both visit every cell once, so both are O(r c). A queue becomes the better choice when the question asks for distances, such as the fewest steps between two cells, because it reaches cells in order of distance.
How would you find the size of the largest island?
We keep the same scan and fill and add one counter. Each time we pop a cell, we add one to the size of the current island, and when the stack empties, we compare that size with the best so far. On our example the largest has 3 cells, and the cost does not change.
What changes if diagonal neighbours count as joined?
Only the STEPS array. We add the four diagonal steps, (1,1), (1,-1), (-1,1) and (-1,-1), so each cell has up to eight neighbours. On our example (1,3) and (2,2) then touch at a corner, islands 2 and 3 merge, and the answer becomes 3. The scan, the seen array and marking on push stay exactly the same, and the time is still O(r c).
9Conclusion
We counted islands the way we would with a highlighter on a map. Judging cells one at a time fails, because joining belongs to the whole group, and relabelling until nothing changes works but sweeps the grid again and again. Seeing the grid as a graph, we scan for unseen land, count it as a new island, and flood fill it with a stack, marking cells as we push them, for O(r c) time and space. The clue to remember is counting groups of joined cells: that is connected components, one traversal from every unvisited node.
Open with
Let me confirm: 1 is land, cells join in four directions, outside is water, and I keep the grid unchanged. Judging cells one by one fails, because a U shaped island has two top left corners.
Then, if they want more
A brute force gives every land cell its own label and sweeps the grid, taking the smallest neighbouring label, until nothing changes; that can need as many sweeps as cells, so it is quadratic.
Instead I treat the grid as a graph, where each land cell is a node joined to its land neighbours and an island is a connected component. I scan the grid, and at each unseen land cell I add one to the count and flood fill its island.
I use an explicit stack rather than recursion, because a large island could overflow the call stack, and I mark a cell when I push it, so none is pushed twice. Each cell is handled a constant number of times, so it is O(rows times columns) time and space. If land arrived one cell at a time I would use union-find.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 54 times in that collection. How it is counted
- Official documentation
- ArrayDeque (Java 21), java.util, package documentation
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 "Count the islands of connected 1s in a binary grid.": https://scrivio-interview-library.netlify.app/data-structures/solutions/count-the-islands-of-connected-1s-in-a-binary-grid-1ea20d/
Coding patterns, question 12 of 15 Back to the path
More graph traversal questions