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
Minimum Operations to Remove Adjacent Ones INPUT Binary Matrix (3x3) 1 1 0 0 1 0 0 0 1 Adjacent 1s connected! grid = [[1,1,0], [0,1,0], [0,0,1]] ALGORITHM STEPS 1 Build Bipartite Graph Cells as nodes, edges for adjacent 1s 2 Find Max Matching Using Hungarian algorithm 3 Max Independent Set |V| - Max Matching 4 Calculate Operations Total 1s - Max Indep Set Bipartite Graph: (0,0) (1,1) (0,1) (2,2) FINAL RESULT Well-Isolated Matrix 1 0 0 0 1 0 0 0 1 Flipped (0,1) from 1 to 0 No adjacent 1s - OK Output: 1 Key Insight: Model as bipartite graph: cells with (row+col) even on one side, odd on other. Adjacent 1s form edges. Maximum Independent Set = Total 1s - Maximum Matching. Operations needed = 4 - 3 = 1 (flip one 1 to break adjacency). TutorialsPoint - Minimum Operations to Remove Adjacent Ones in Matrix | Maximum Independent Set (Bipartite Graph)
Asked in
Google 15 Meta 12 Amazon 8
3.2K Views
Medium Frequency
~35 min Avg. Time
89 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen