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: Problem OverviewInput: 2D Grid1111110001100011000111111Analysis🟨 Orange cells: Connected to boundary🟩 Green cell: Closed island (count = 1)🟦 Blue cells: Water (1s)Algorithm:1. Find all land cells (0s)2. Check if island touches boundary3. Count islands that don't touch edgesResult: 1 Closed IslandThe single green cell forms a closed island
Understanding the Visualization
1
Input Grid
2D grid with 0s (land) and 1s (water)
2
Identify Islands
Find connected groups of land cells (0s)
3
Check Boundaries
Determine which islands touch grid edges
4
Count Closed
Count islands that don't touch boundaries
Key Takeaway
🎯 Key Insight: A closed island is completely surrounded by water and doesn't touch any grid boundary
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