Minimum Operations to Remove Adjacent Ones in Matrix Problem
Description
LeetCode Problem 2123.
You are given a 0-indexed binary matrix grid. In one operation, you can flip any 1 in grid to be 0.
A binary matrix is well-isolated if there is no 1 in the matrix that is 4-directionally connected (i.e., horizontal and vertical) to another 1.
Return the minimum number of operations to make grid well-isolated.
Example 1:

Input: grid = [[1,1,0],[0,1,1],[1,1,1]]
Output: 3
Explanation: Use 3 operations to change grid[0][1], grid[1][2], and grid[2][1] to 0.
After, no more 1's are 4-directionally connected and grid is well-isolated.
Example 2:

Input: grid = [[0,0,0],[0,0,0],[0,0,0]]
Output: 0
Explanation: There are no 1's in grid and it is well-isolated.
No operations were done so return 0.
Example 3:

Input: grid = [[0,1],[1,0]]
Output: 0
Explanation: None of the 1's are 4-directionally connected and grid is well-isolated.
No operations were done so return 0.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 300grid[i][j]is either0or1.
Solution
Approach: Bipartite Matching
Color the cells like a chessboard. Two adjacent 1s always have different colors, so the 1s form a bipartite graph with an edge between every pair of adjacent 1s. Removing a 1 is picking a vertex, and we need to pick vertices so that every edge is covered: a minimum vertex cover. By Konig's theorem its size equals the size of a maximum matching, which we find with the Hungarian algorithm: from each unmatched vertex on one side, look for an augmenting path.
Complexity: time O(V * E), where V is the number of 1s and E the number of adjacent pairs; space O(mn).
from collections import defaultdict
class Solution:
def minimumOperations(self, grid: List[List[int]]) -> int:
def find(i: int) -> int:
for j in g[i]:
if j not in vis:
vis.add(j)
if match[j] == -1 or find(match[j]):
match[j] = i
return 1
return 0
g = defaultdict(list)
m, n = len(grid), len(grid[0])
for i, row in enumerate(grid):
for j, v in enumerate(row):
if (i + j) % 2 and v:
x = i * n + j
if i < m - 1 and grid[i + 1][j]:
g[x].append(x + n)
if i and grid[i - 1][j]:
g[x].append(x - n)
if j < n - 1 and grid[i][j + 1]:
g[x].append(x + 1)
if j and grid[i][j - 1]:
g[x].append(x - 1)
match = [-1] * (m * n)
ans = 0
for i in g.keys():
vis = set()
ans += find(i)
return ans