Given a 2D grid consisting of 0s (land) and 1s (water), an island is a maximal 4-directionally connected group of 0s.

A closed island is an island that is totally surrounded by 1s on all sides (left, top, right, bottom).

Return the number of closed islands.

Input & Output

Example 1 — Basic Closed Island
$ 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
💡 Note: There are two closed islands: one 2x2 island in the middle-left area, and one single cell island. The rightmost land cells touch the boundary so they don't count.
Example 2 — No Closed Islands
$ Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
Output: 0
💡 Note: All land cells are connected to the boundary (top, bottom, left, or right edges), so there are no closed islands.
Example 3 — Single Closed Island
$ Input: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
Output: 1
💡 Note: The center island is completely surrounded by water (1s). The single land cell in the middle is also connected to the outer ring, forming one large closed island.

Constraints

  • 1 ≤ grid.length, grid[i].length ≤ 100
  • grid[i][j] is 0 or 1

Visualization

Tap to expand
Number of Closed Islands 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 1 = Water 0 = Border Land Closed Island 1 Closed Island 2 5 x 8 Grid 0=land, 1=water grid[5][8] TWO-PASS DFS 1 Pass 1: Mark Border DFS from all border 0s Mark as visited (not closed) X Border 0s 2 Pass 2: Count Islands Scan remaining 0s Each new 0 = closed island 3 DFS Exploration 4-directional: up, down, left, right neighbors 4 Increment Counter count++ for each closed island found Time: O(m*n) Space: O(m*n) FINAL RESULT Identified Islands: Island 1 L-shaped 7 cells [OK] Closed Island 2 Single cell 1 cell [OK] Closed OUTPUT 2 Not Counted (Border): Right edge 0s at col 7 Connected to boundary 2 closed islands found completely surrounded by water on all sides Key Insight: Two-Pass DFS eliminates boundary-connected land first. Any remaining land cells must be completely surrounded by water, forming closed islands. Pass 1 marks border-connected 0s as visited. Pass 2 counts remaining unvisited 0s as closed islands. TutorialsPoint - Number of Closed Islands | Two-Pass DFS Approach
Asked in
Amazon 15 Microsoft 12 Google 8 Facebook 6
89.2K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen