Number of Closed Islands solution explained
To count closed islands, flood-fill each land region once and track whether any of its cells lies on the outer edge of the grid; count the region only if none does. An equally good order is to first sink every land region connected to the border, then count the regions that remain. Either way each cell is visited a constant number of times, so the solution is O(rows × columns) time.
By Evin JohnPublished 9 min read
What counts as a closed island
The input is a rectangular grid of cells. In the common version of this problem, a 0 is land and a 1 is water. Land cells that share a side belong to the same island; touching at a corner does not connect them. An island is closed when none of its cells sits in the first row, last row, first column or last column. In other words, you could walk all the way around it on water without leaving the map. Return how many closed islands there are.
1 1 1 1 1 1 0
1 0 0 1 1 1 0
1 0 1 1 0 1 1
1 1 1 1 0 1 1
0 0 1 1 1 1 1
Four islands in total:
cells (1,1), (1,2), (2,1) closed
cells (2,4), (3,4) closed
cells (0,6), (1,6) touches the top and right edge
cells (4,0), (4,1) touches the bottom and left edge
Answer: 2Two quick consequences. A grid with fewer than three rows or three columns has no interior, so the answer is 0. And the shape of the water inside an island does not matter: an island shaped like a ring with a lake in the middle is still one closed island if the ring stays off the edge.
How this differs from Number of Islands
If you have solved Number of Islands, the search itself is familiar. What changes is the decision attached to each search. There, every flood fill adds one to the count. Here, a flood fill only counts if the whole region stays inside the border, so each search has to report a yes-or-no along with marking cells. That small change is where most bugs come from, as the mistakes section shows. The flipped meaning of 0 and 1 is the other trap: code copied from the earlier problem will count water.
Interviewers use the problem to see whether you adapt a known algorithm or paste it. Follow-ups usually include:
- Count the land cells in closed islands instead of the islands. Sink border land first, then count every remaining 0.
- Capture surrounded regions. Turn every closed region into water and return the grid; same search, a different output.
- Diagonal connections. Use eight directions. Closed islands can merge with edge islands through a corner, so answers change.
- Huge grids. Avoid recursion; a 1,000 by 1,000 all-land interior would need a million nested calls.
- Union-find. Join each border land cell to a virtual "outside" node, union neighbors, then count land roots not joined to outside.
Slow but obviously right
For every land cell, run a fresh breadth-first search that collects that cell's whole island. Count the island only from the cell that comes first in row-major order, so each island is counted once, and only if no collected cell is on the border. Nothing is shared between searches, so a big island is searched once per cell it contains. That makes the worst case O((rows × columns)²), which is far too slow for large inputs but perfect as an independent test oracle.
from collections import deque
DIRS = ((1, 0), (-1, 0), (0, 1), (0, -1))
def island_of(grid, r, c):
rows, cols = len(grid), len(grid[0])
seen = {(r, c)}
queue = deque([(r, c)])
while queue:
x, y = queue.popleft()
for dx, dy in DIRS:
nx, ny = x + dx, y + dy
if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == 0 and (nx, ny) not in seen:
seen.add((nx, ny))
queue.append((nx, ny))
return seen
def closed_islands_brute(grid):
rows, cols = len(grid), len(grid[0])
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != 0:
continue
cells = island_of(grid, r, c)
if min(cells) != (r, c):
continue
if all(0 < x < rows - 1 and 0 < y < cols - 1 for x, y in cells):
count += 1
return countLinear approach 1: one search per island with a border flag
Scan the grid. At each unvisited land cell, start a breadth-first search with a flag set to closed. Every time the search takes a cell off the queue, check whether that cell is on the border, and if so set the flag to open. Crucially, do not stop the search when that happens. The search must still mark every cell of the island as visited, or the scan will later find the unmarked remainder and treat it as a new island. When the queue empties, add one to the count if the flag is still closed.
def closed_islands(grid):
rows, cols = len(grid), len(grid[0])
seen = [[False] * cols for _ in range(rows)]
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != 0 or seen[r][c]:
continue
seen[r][c] = True
queue = deque([(r, c)])
closed = True
while queue:
x, y = queue.popleft()
if x == 0 or y == 0 or x == rows - 1 or y == cols - 1:
closed = False
for dx, dy in DIRS:
nx, ny = x + dx, y + dy
if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == 0 and not seen[nx][ny]:
seen[nx][ny] = True
queue.append((nx, ny))
if closed:
count += 1
return countLinear approach 2: sink the border first
Any island that touches the border contains a border cell. So walk around the four edges, and from every land cell found there, flood-fill its island and turn it into water. After that, every land cell left in the grid belongs to a closed island, and the remaining task is plain island counting over the interior. The JavaScript version works on a copy so the caller's grid is not changed, and it uses an explicit stack so large regions do not overflow the call stack.
function closedIsland(grid) {
const rows = grid.length;
const cols = grid[0].length;
const land = grid.map((row) => row.slice());
const steps = [[1, 0], [-1, 0], [0, 1], [0, -1]];
const sink = (r, c) => {
land[r][c] = 1;
const stack = [[r, c]];
while (stack.length > 0) {
const [x, y] = stack.pop();
for (const [dx, dy] of steps) {
const nx = x + dx;
const ny = y + dy;
if (nx >= 0 && ny >= 0 && nx < rows && ny < cols && land[nx][ny] === 0) {
land[nx][ny] = 1;
stack.push([nx, ny]);
}
}
}
};
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const onEdge = r === 0 || c === 0 || r === rows - 1 || c === cols - 1;
if (onEdge && land[r][c] === 0) sink(r, c);
}
}
let count = 0;
for (let r = 1; r < rows - 1; r++) {
for (let c = 1; c < cols - 1; c++) {
if (land[r][c] === 0) {
count++;
sink(r, c);
}
}
}
return count;
}Run it on the example. The edge pass finds land at (0,6) and (4,0) and sinks those two islands, along with (1,6) and (4,1). The interior pass then meets (1,1), counts it and sinks its island, and later meets (2,4), counts it and sinks that one. The count is 2.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Fresh search from every land cell | O((R·C)²) worst case | O(R·C) per search |
| One BFS per island with a border flag | O(R·C) | O(R·C) visited grid plus the queue |
| Sink border land, then count | O(R·C) | O(R·C) for the copy (O(1) extra if you may modify the input) plus the stack |
| Union-find with a virtual outside node | O(R·C·α(R·C)), effectively linear | O(R·C) for the parent array |
Edge cases
- One row or one column, or any grid with fewer than three rows or columns: 0.
- All water: 0. All land: 0, since the single island covers the border.
- An island that touches the border at a single cell: open, not closed.
- Two interior regions that meet only at a corner: two separate islands.
- An island wrapping around a lake: still one island.
- A large interior region: check that the search is iterative.
Mistakes to watch for
- Returning from the flood fill as soon as it touches the edge. The rest of the island stays unvisited, and the scan later counts those cells as a separate closed island.
- Writing the recursive version as return up() and down() and left() and right(). Short-circuit evaluation skips the remaining directions after the first false, which causes the same partial marking.
- Copying Number of Islands code and counting 1s, which counts water regions.
- Treating a cell outside the grid as water, which makes edge islands look closed.
- Mutating the caller's grid without saying so.
Explaining it out loud
Fictional example
- Candidate
- First, in this version 0 is land, right? Then this is island counting, except an island only counts if it never touches the edge.
- Candidate
- I will run a BFS per island and keep a flag. If any cell is on the border I clear the flag, but I keep searching so the whole island gets marked.
- Interviewer
- Why keep going?
- Candidate
- If I stop early, the unmarked part of that island looks like a new island when the scan reaches it, and it might not touch the border, so I would overcount.
- Candidate
- Every cell is queued at most once, so it is linear in the grid size. Another option is to sink everything connected to the border first and then count the rest.
Related walkthroughs
Number of Islands is the base problem this one adapts. N-ary Tree Level Order Traversal uses the same breadth-first queue on a tree, and Is Graph Bipartite attaches a yes-or-no verdict to each connected component, just as the border flag does here. House Robber IV is a change of pace from grids, built on binary search over the answer.
Natively as a practice aid
On a Mac or Windows PC, Natively can read a grid problem like this from a screenshot while you practice and give an approach and code in its overlay, which helps when you want to compare the border-flag and sink-first strategies. You can also ask it one focused question, for example why stopping a flood fill early overcounts. It transcribes spoken mock rounds too, so you can check whether you confirmed the 0-and-1 meaning before writing code. See the AI interview assistant.
Questions people ask
How do you count closed islands in a grid?
Flood-fill each land region once and note whether any of its cells is on the grid's border; count it only if none is. Or sink all border-connected land first and count the islands that remain.
In Number of Closed Islands, is 0 land or water?
In the common version 0 is land and 1 is water, the reverse of Number of Islands. Confirm the encoding before you code.
What is the time complexity of Number of Closed Islands?
O(rows × columns) time, since each cell is visited a constant number of times, and up to O(rows × columns) space for the visited grid and queue.
Why should the flood fill not stop when it reaches the border?
Stopping early leaves part of the island unmarked. The scan later finds that part, treats it as a new island, and may count it as closed.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
