← Visualizers
Graphs · Flood fill on a grid LeetCode 1254

Number of Closed Islands / visualized

An island (0s) is closed if completely surrounded by 1s (water). The boundary test is folded into the recursive return: Crucial invariant: you cannot short-circuit with &&, or leaking islands are left partially unsunk and spawn phantom closed islands later.

Execution

idle
INVARIANT Closed Island Invariant: An island is closed iff 0 cells touch the grid border. You must evaluate all 4 directions with non-short-circuit bitwise &, or leaking pieces remain unsunk to falsely trigger later!
Call Stack · Border Check Traversal Top = Active · Bottom = Suspended Parents
Press Run to begin.
0 / 0
Speed

Java · running line

scanning cell current cell flooding confirmed closed water / open
INTERVIEW SCRIPT

How to Explain Closed Islands to an Interviewer

1. Watch the Inverted Values

"Notice the LeetCode convention here: 0 is land, and 1 is water. A closed island is an island of 0s surrounded on all 4 sides by 1s."

2. The Border Contact Invariant

"Any cell at r == 0, r == m-1, c == 0, c == n-1 touches the boundary and leaks. If a component touches the boundary, it can never be closed."

3. Why Non-Short-Circuit & is Vital

"Even if a cell is detected on the border, we MUST continue recursing all 4 neighbors with bitwise &. If we short-circuited with &&, the remainder of the leaking island would be left unsunk, causing future scans to count disconnected pieces as new islands!"

4. Space & Time Complexity

"Time is $O(m \cdot n)$ since every cell is sunk once. Auxiliary space is $O(m \cdot n)$ Call Stack depth in the worst-case continuous component."

O(m·n) time · O(m·n) stack  ·  0 is land and 1 is water. Evaluating all 4 directions with bitwise & ensures leaking islands are fully sunk so fragments are not counted later.