Minimum Operations to Remove Adjacent Ones in Matrix - Problem
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.
Input & Output
Example 1 — Basic Adjacent 1s
$
Input:
grid = [[1,1,0],[0,1,0],[0,0,1]]
›
Output:
1
💡 Note:
Remove the center 1 at position (1,1). This breaks both adjacencies: (0,0)-(0,1) and (0,1)-(1,1), making the matrix well-isolated with only isolated 1s remaining.
Example 2 — Multiple Groups
$
Input:
grid = [[1,1],[1,1]]
›
Output:
2
💡 Note:
All four 1s are connected. We need to remove at least 2 of them to make remaining 1s non-adjacent. One optimal solution is to keep (0,0) and (1,1) which are diagonally positioned.
Example 3 — Already Well-Isolated
$
Input:
grid = [[1,0,1],[0,0,0],[1,0,1]]
›
Output:
0
💡 Note:
All 1s are already isolated with no adjacent pairs. No operations needed.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 15
- grid[i][j] is either 0 or 1
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
Binary matrix with adjacent 1s that need separation
2
Find Minimum Removals
Identify which 1s to remove to eliminate all adjacencies
3
Well-Isolated Result
Final matrix with no adjacent 1s
Key Takeaway
🎯 Key Insight: Model as maximum independent set in bipartite graph to minimize removals
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code