Number of Closed Islands
Medium
Topics
Given a grid where 0 is land and 1 is water, an island is a maximal group of 4-directionally connected land cells. Return the number of closed islands — islands that are entirely surrounded by water (no land cell touches the grid border).
Example 1
0 is land and 1 is water. An island counts only if it is completely surrounded by water, so any group touching the grid border is excluded. That leaves 2.Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]] Output: 2
Example 2
Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: 1
Constraints
- 1 <= m, n <= 100
- grid[i][j] is 0 or 1.
Editorial — intuition, approach, complexity and pitfalls
Intuition
An island is closed exactly when none of its cells sit on the grid border. So flood each land component once and, while flooding, watch whether any cell of it is on an edge. One pass over the grid, one flood per component.
The shown solution uses an explicit stack rather than recursion, and that is not style. A recursive flood fill spends one call frame per cell, and at the stated limit of 100×100 an all-land grid is a single 10,000-cell component, and the recursive version raises RecursionError in Python at the default limit and crashes Node outright. Moving the frontier to an explicit stack puts that same O(m·n) memory on the heap, where it is unremarkable.
Approach
- Scan the grid for an unvisited land cell.
- Mark it and push it; then, while the stack is non-empty, pop a cell and check whether it lies on row 0, the last row, column 0 or the last column — if so the component is open.
- Push each unvisited land neighbour, marking it at push time.
- When the stack drains, the component is finished; count it if it never touched the border.
Dry Run
grid (0 is land, 1 is water)
1 1 1 1 1
1 0 0 0 1
1 0 1 0 1
1 1 1 1 1
one land component: the ring of 0s at rows 1-2
no cell of it is on row 0, row 3, column 0 or column 4
-> closed
answer 1Complexity
- Time — O(m·n): every cell is marked once, pushed once and popped once.
- Space — O(m·n): the stack, in the worst case where the whole grid is one component. The grid itself is reused as the visited marker, so there is no separate visited array.
Common Pitfalls
- Writing it recursively. Measured above: it dies inside the stated constraints in Python and Node. The space bound O(m·n) is correct either way — the difference is which stack it lands on.
- Marking cells when they are popped rather than when they are pushed. The same cell then enters the stack once per land neighbour, which inflates the stack and the work by a constant factor that is avoidable for free.
- Counting components that touch the border.
- Resetting the border flag once per grid instead of once per component, so a single open island poisons every island found after it.
- Reading
0as water. In this problem0is land and1is water, the reverse of the usual convention — and the reverse of the sibling problem number of enclaves. - Checking for the border by letting the walk step out of bounds and setting a flag there. It works, but testing
r == 0 || r == R-1 || c == 0 || c == C-1on the cell itself is the same check without the out-of-range excursion.
Full Solution — all languages
class Solution:
def closedIsland(self, grid):
R, C = len(grid), len(grid[0])
count = 0
for sr in range(R):
for sc in range(C):
if grid[sr][sc] != 0:
continue
# Explicit stack, not recursion. A 100x100 all-land grid is one
# component 10,000 cells deep, which overflows the call stack.
closed = True
grid[sr][sc] = 2
stack = [(sr, sc)]
while stack:
r, c = stack.pop()
if r == 0 or r == R - 1 or c == 0 or c == C - 1:
closed = False
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == 0:
grid[nr][nc] = 2 # mark on push, never on pop
stack.append((nr, nc))
if closed:
count += 1
return countimport java.util.*;
class Solution {
private static final int[] DR = {1, -1, 0, 0};
private static final int[] DC = {0, 0, 1, -1};
public int closedIsland(int[][] grid) {
int R = grid.length, C = grid[0].length, count = 0;
// Explicit stack, not recursion. One component can cover every cell, and
// R*C nested frames overflow the call stack.
int[] stack = new int[R * C];
for (int sr = 0; sr < R; sr++) {
for (int sc = 0; sc < C; sc++) {
if (grid[sr][sc] != 0) continue;
boolean closed = true;
int top = 0;
grid[sr][sc] = 2;
stack[top++] = sr * C + sc;
while (top > 0) {
int cell = stack[--top];
int r = cell / C, c = cell % C;
if (r == 0 || r == R - 1 || c == 0 || c == C - 1) closed = false;
for (int d = 0; d < 4; d++) {
int nr = r + DR[d], nc = c + DC[d];
if (nr >= 0 && nr < R && nc >= 0 && nc < C && grid[nr][nc] == 0) {
grid[nr][nc] = 2; // mark on push, never on pop
stack[top++] = nr * C + nc;
}
}
}
if (closed) count++;
}
}
return count;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int closedIsland(vector<vector<int>>& grid) {
int R = grid.size(), C = grid[0].size(), count = 0;
const int DR[4] = {1, -1, 0, 0}, DC[4] = {0, 0, 1, -1};
// Explicit stack, not recursion. One component can cover every cell, and
// R*C nested frames overflow the call stack.
vector<int> stk;
stk.reserve(R * C);
for (int sr = 0; sr < R; sr++) {
for (int sc = 0; sc < C; sc++) {
if (grid[sr][sc] != 0) continue;
bool closed = true;
grid[sr][sc] = 2;
stk.clear();
stk.push_back(sr * C + sc);
while (!stk.empty()) {
int cell = stk.back(); stk.pop_back();
int r = cell / C, c = cell % C;
if (r == 0 || r == R - 1 || c == 0 || c == C - 1) closed = false;
for (int d = 0; d < 4; d++) {
int nr = r + DR[d], nc = c + DC[d];
if (nr >= 0 && nr < R && nc >= 0 && nc < C && grid[nr][nc] == 0) {
grid[nr][nc] = 2; // mark on push, never on pop
stk.push_back(nr * C + nc);
}
}
}
if (closed) count++;
}
}
return count;
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var closedIsland = function(grid) {
const R = grid.length, C = grid[0].length;
const DR = [1, -1, 0, 0], DC = [0, 0, 1, -1];
let count = 0;
for (let sr = 0; sr < R; sr++) {
for (let sc = 0; sc < C; sc++) {
if (grid[sr][sc] !== 0) continue;
// Explicit stack, not recursion. One component can cover every cell,
// and R*C nested frames overflow the call stack.
let closed = true;
grid[sr][sc] = 2;
const stack = [sr * C + sc];
while (stack.length) {
const cell = stack.pop();
const r = (cell / C) | 0, c = cell % C;
if (r === 0 || r === R - 1 || c === 0 || c === C - 1) closed = false;
for (let d = 0; d < 4; d++) {
const nr = r + DR[d], nc = c + DC[d];
if (nr >= 0 && nr < R && nc >= 0 && nc < C && grid[nr][nc] === 0) {
grid[nr][nc] = 2; // mark on push, never on pop
stack.push(nr * C + nc);
}
}
}
if (closed) count++;
}
}
return count;
};