Number of Closed Islands (LeetCode 1254): Solution and Explanation
In a grid where 0 is land and 1 is water, count the islands that are fully enclosed by water, meaning no cell of the island sits on the outer edge of the grid.
Intuition
Note the flipped encoding: here 0 is land and 1 is water. An island is still a group of land cells joined up, down, left or right.
Water surrounds an island on every side unless the island reaches the edge of the grid. Off the map there is no water, so an island with even one cell in the first or last row or column is open.
That turns the question into a flood fill with one extra bit: while you mark every cell of an island, remember whether any of them was on the border.
The flood must cover the whole island even after you learn it is open. Stopping early would leave unmarked land that the scan later counts as a separate island.
Approach: Flood fill with a closed flag
- Scan every cell in row-major order and skip water and cells already visited.
- At an unvisited land cell, set
closed = true, mark the cell, and push it on a stack. - Pop cells until the stack is empty. If a popped cell is in row 0, column 0, the last row or the last column, set
closed = false. Push each unvisited land neighbour after marking it. - When the stack empties, the whole island is marked. If
closedis still true, add one to the count. - Return the count after the scan.
Step-by-step example
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]]
- The scan first meets land at (0, 7). Its island is (0, 7), (1, 7), (2, 7). All three are in the last column, so the island is open and the count stays 0.
- Next it meets (1, 1). The flood covers the ring of ten cells in rows 1 to 3, columns 1 to 4. None of them is on the border, so the count becomes 1.
- At (3, 6) a single land cell is walled in by water on all four sides, so the count becomes 2.
- Finally (4, 7) is a one-cell island in the bottom-right corner. It is on the edge, so it does not count. The answer is 2.
Code: Python, Java, C++
1class Solution:
2 def closedIsland(self, grid: List[List[int]]) -> int:
3 m, n = len(grid), len(grid[0])
4 count = 0
5 for i in range(m):
6 for j in range(n):
7 if grid[i][j] != 0:
8 continue
9 closed = True
10 grid[i][j] = 1
11 stack = [(i, j)]
12 while stack:
13 r, c = stack.pop()
14 if r == 0 or c == 0 or r == m - 1 or c == n - 1:
15 closed = False
16 for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
17 if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 0:
18 grid[nr][nc] = 1
19 stack.append((nr, nc))
20 if closed:
21 count += 1
22 return count1class Solution {
2 public int closedIsland(int[][] grid) {
3 int m = grid.length, n = grid[0].length, count = 0;
4 int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
5 for (int i = 0; i < m; i++) {
6 for (int j = 0; j < n; j++) {
7 if (grid[i][j] != 0) continue;
8 boolean closed = true;
9 grid[i][j] = 1;
10 Deque<int[]> stack = new ArrayDeque<>();
11 stack.push(new int[]{i, j});
12 while (!stack.isEmpty()) {
13 int[] cell = stack.pop();
14 int r = cell[0], c = cell[1];
15 if (r == 0 || c == 0 || r == m - 1 || c == n - 1) closed = false;
16 for (int[] d : dirs) {
17 int nr = r + d[0], nc = c + d[1];
18 if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == 0) {
19 grid[nr][nc] = 1;
20 stack.push(new int[]{nr, nc});
21 }
22 }
23 }
24 if (closed) count++;
25 }
26 }
27 return count;
28 }
29}1class Solution {
2public:
3 int closedIsland(vector<vector<int>>& grid) {
4 int m = grid.size(), n = grid[0].size(), count = 0;
5 int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
6 for (int i = 0; i < m; i++) {
7 for (int j = 0; j < n; j++) {
8 if (grid[i][j] != 0) continue;
9 bool closed = true;
10 grid[i][j] = 1;
11 vector<pair<int, int>> stack = {{i, j}};
12 while (!stack.empty()) {
13 auto [r, c] = stack.back(); stack.pop_back();
14 if (r == 0 || c == 0 || r == m - 1 || c == n - 1) closed = false;
15 for (auto& d : dirs) {
16 int nr = r + d[0], nc = c + d[1];
17 if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == 0) {
18 grid[nr][nc] = 1;
19 stack.push_back({nr, nc});
20 }
21 }
22 }
23 if (closed) count++;
24 }
25 }
26 return count;
27 }
28};Time and space complexity
O(m * n)
Every cell is scanned once and every land cell is pushed and popped once, with four neighbour checks each.
O(m * n)
The explicit stack can hold a large part of the grid when one island fills most of it. Marking cells in place avoids a separate visited array.
Other approaches
Sink the edge islands first (time O(m * n), space O(m * n))
Flood every island that touches the border and turn it into water. Every island left afterwards is closed, so a second pass simply counts islands.
Union-Find (time O(m * n * α(m * n)), space O(m * n))
Union neighbouring land cells and link every border land cell to a virtual 'edge' node. Count the land roots that are not connected to the edge node.
Recursive DFS (time O(m * n), space O(m * n))
The same flood written recursively, returning whether the island is closed. Short, but a 100 x 100 island can exceed Python's default recursion limit.
Common mistakes
- Mixing up the encoding. In this problem
0is land and1is water, the opposite of Number of Islands. - Returning from the flood as soon as an edge cell is found. The rest of the island stays unmarked and gets counted later.
- Writing
return dfs(a) and dfs(b) and ...in a recursive version. Short-circuit evaluation skips the remaining neighbours, which causes the same bug. - Treating a single row or single column grid specially. Every cell there is on the edge, and the general check already handles it.
Frequently asked questions
Why is touching the edge the only thing that matters?
Inside the grid, any land cell's neighbours are either land of the same island or water. The only place an island can lack water on a side is where that side is off the grid.
Can I use BFS instead of a stack?
Yes. The order of visiting does not matter, only that every cell of the island is marked and checked for the edge. A queue works just as well as a stack.
Is it fine to modify the input grid?
It saves a visited array, and LeetCode allows it. If the caller needs the grid afterwards, copy it first or use a separate boolean matrix.
How does this differ from Number of Enclaves?
Number of Enclaves counts land cells that cannot reach the edge, so it sums sizes. This problem counts islands, so each enclosed island adds one regardless of its size.