Problem Description
Given a 0-indexed binary matrix grid, you can flip any 1 in grid to 0 in one operation. A binary matrix is well-isolated if no 1 in the matrix is 4-directionally connected (i.e. horizontally or vertically) to another 1. Return the minimum number of operations required to make grid well-isolated.
Key Insights
- The goal is to remove the minimum number of ones so that the remaining ones are not adjacent (up, down, left, right).
- Instead of thinking about removals directly, we can view the problem as keeping the maximum number of ones that are isolated.
- The selected ones must form an independent set in a graph where nodes represent ones and edges represent adjacent ones.
- The grid can be bipartitioned (using a chessboard pattern) since any cell’s neighbors have the opposite color.
- For a bipartite graph, the Maximum Independent Set size equals the total number of ones minus the Minimum Vertex Cover (by Kőnig’s theorem). And the minimum vertex cover size equals the maximum matching.
- Hence, the minimum removals equal the size of the maximum matching in the bipartite graph induced by ones.
Space and Time Complexity
Time Complexity: O(V * E) in the worst-case using DFS-based augmenting path search; optimizations (like Hopcroft–Karp) can improve average-case performance. Space Complexity: O(V + E) for storing graph nodes and edges.
Solution
We use a bipartite matching approach. First, we assign cells with ones to two sets (based on (row+col) % 2). For each cell with a 1 in one set, we attempt to find an augmenting path to a neighboring 1 in the other set via DFS. The maximum number of matchings found corresponds to the minimum ones to remove (equal to the size of the maximum matching). We explicitly build edges for valid neighboring positions (up, down, left, right) and then run DFS-based matching to compute the maximum matching. Finally, the answer is the maximum matching count.