Minimum Number of Days to Disconnect Island - Problem

You are given an m x n binary grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally connected group of land cells (horizontal or vertical connections only).

The grid is considered connected if it contains exactly one island, otherwise it's disconnected.

Your mission: Find the minimum number of days needed to disconnect the grid, where each day you can convert exactly one land cell (1) into water (0).

Key insight: The answer is always 0, 1, or 2! If the grid is already disconnected, return 0. If removing any single land cell disconnects it, return 1. Otherwise, you can always disconnect any connected island by removing at most 2 strategically chosen cells.

Input & Output

example_1.py โ€” Simple 2x2 Grid
$ Input: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]
โ€บ Output: 2
๐Ÿ’ก Note: The island is a 2x2 square. No single cell removal can disconnect it, but removing any 2 adjacent cells will split it into separate parts.
example_2.py โ€” Linear Island
$ Input: grid = [[1,1]]
โ€บ Output: 2
๐Ÿ’ก Note: Even though it's just 2 cells, we need to remove both to have 0 islands (which counts as disconnected).
example_3.py โ€” Already Disconnected
$ Input: grid = [[1,0,1,0]]
โ€บ Output: 0
๐Ÿ’ก Note: There are already 2 separate islands, so the grid is already disconnected.

Visualization

Tap to expand
Island Disconnection VisualizationLinear Island - Remove 1 Bridge2x2 Square - Need 2 RemovalsKey InsightAnswer is always 0, 1, or 20: Already disconnected1: Has articulation point2: Mathematical guarantee
Understanding the Visualization
1
Analyze Structure
Count current islands - if not exactly 1, already disconnected
2
Find Critical Points
Test each land cell - some act as crucial bridges
3
Apply Mathematics
Graph theory guarantees any connected component can be split with โ‰ค2 removals
Key Takeaway
๐ŸŽฏ Key Insight: The mathematical guarantee that any connected graph can be disconnected by removing at most 2 vertices simplifies this problem dramatically!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(mยฒnยฒ)

For each of O(mn) pairs of cells, we run DFS/BFS which takes O(mn) time

n
2n
โš  Quadratic Growth
Space Complexity
O(mn)

Space for visited array in DFS/BFS traversal

n
2n
โšก Linearithmic Space

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 โ‰ค m, n โ‰ค 30
  • grid[i][j] is either 0 or 1
  • The grid has at most one island
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 5
28.4K Views
Medium Frequency
~25 min Avg. Time
890 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