Number of Closed Islands

Medium

Topics
GraphDFSBFSUnion FindMatrix

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

01111111011000011021010111031000010141111111001234567
closed — countedtouches the border — not counted
Here 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.
2D grid — one row per line.
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

011111012111012
closed — counted
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

  1. Scan the grid for an unvisited land cell.
  2. 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.
  3. Push each unvisited land neighbour, marking it at push time.
  4. 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 1

Complexity

  • 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 0 as water. In this problem 0 is land and 1 is 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-1 on 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 count
SensAI
Beta
Tap the mic to stop voice mode