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
Visualization
Time & Space Complexity
For each of O(mn) pairs of cells, we run DFS/BFS which takes O(mn) time
Space for visited array in DFS/BFS traversal
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