Imagine exploring a vast archipelago where islands are scattered across the ocean! You're given a 2D grid representing this maritime landscape, where 0 represents land and 1 represents water.

An island is a group of connected land cells (0s) that are adjacent horizontally or vertically. But here's the twist: we're only interested in closed islands - islands that are completely surrounded by water on all sides, including the boundaries of the grid.

Goal: Count how many closed islands exist in this grid. An island touching the edge of the grid doesn't count as closed since it's not completely surrounded by water!

Example: In a grid where land extends to the border, those border islands are not closed because they're not fully encircled by water.

Input & Output

example_1.py β€” Basic Grid
$ Input: grid = [[1,1,1,1,1],[1,0,0,1,1],[1,0,0,1,1],[1,1,1,1,1]]
β€Ί Output: 1
πŸ’‘ Note: The 2x2 land area in the middle is completely surrounded by water, making it a closed island. Count = 1.
example_2.py β€” Multiple Islands
$ Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
β€Ί Output: 0
πŸ’‘ Note: All land areas touch the boundary (edges of grid), so no islands are completely closed. Count = 0.
example_3.py β€” Complex Layout
$ 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: Two closed islands exist: one small island and one larger island, both completely surrounded by water.

Constraints

  • 1 ≀ grid.length, grid[i].length ≀ 100
  • grid[i][j] is 0 (land) or 1 (water)
  • Islands are formed by connecting adjacent land cells horizontally or vertically

Visualization

Tap to expand
🏝️ Closed Island Detection ProcessStep 1: Original Grid🟦 Water 🟩 LandStep 2: Mark Boundary IslandsπŸ”΄ Boundary ConnectedStep 3: Count Closed Islands1🟨 1 Closed Island Found!πŸ” Algorithm Steps:1. Start DFS from all boundary cells containing land (0)2. Mark all connected land as eliminated (boundary islands)3. Count remaining unmarked land clusters = closed islandsβœ… Time: O(mΓ—n) | Space: O(mΓ—n)
Understanding the Visualization
1
Boundary Sweep
Start from all edges and mark connected land as 'boundary islands'
2
Elimination Phase
All boundary-connected land becomes water (eliminated)
3
Counting Phase
Count remaining isolated land masses - these are closed islands
Key Takeaway
🎯 Key Insight: Instead of checking if each island is closed, eliminate all open (boundary-connected) islands first, then count what remains!
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28 Apple 22
28.5K Views
Medium-High Frequency
~18 min Avg. Time
1.2K 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