Problem Description
Given an m x n binary grid where 1 represents land and 0 represents water, an island is defined as a maximal 4-directionally connected group of 1's. The grid is "connected" if there is exactly one island; otherwise, it is "disconnected". In one day, you can convert a single land cell into water. The task is to return the minimum number of days required to disconnect the grid.
Key Insights
- First, determine if the grid is already disconnected by counting islands using DFS/BFS.
- If there is not exactly one island, return 0 (either already disconnected or completely water).
- For a grid with exactly one island, simulate the removal of each land cell one by one. For each removal, check if the island becomes disconnected.
- If any removal causes a disconnection, return 1.
- If no single removal disconnects the island, then the answer must be 2.
- Using DFS/BFS allows you to explore connected components efficiently.
Space and Time Complexity
Time Complexity: O((m * n)^2) in the worst-case scenario, as for each cell removal, a full DFS/BFS traversal (O(m * n)) is done. Space Complexity: O(m * n) due to recursion/auxiliary space for DFS/BFS and the visited tracking.
Solution
The solution begins by performing a DFS (or BFS) to count the number of islands in the grid. If the grid is already disconnected (i.e., the number of islands is not 1), return 0. Next, iterate over every land cell and temporarily change it to water. For each modified grid, perform another DFS/BFS to see if the connected component is broken. If you find a removal that leads to a disconnected grid, return 1. If none of the single removals disconnect the island, then return 2. This works because in the worst case, two removals are sufficient to disconnect the island.