Minimum Operations to Remove Adjacent Ones in Matrix - Problem

You are given a binary matrix where each cell contains either 0 or 1. Your mission is to make the matrix "well-isolated" by strategically flipping 1s to 0s.

A matrix is considered well-isolated when no 1 has any neighboring 1s in the four cardinal directions (up, down, left, right). Think of it like ensuring no two islands touch each other!

Goal: Find the minimum number of flip operations needed to achieve this well-isolated state.

Example: In matrix [[1,1,0],[0,1,1],[0,0,1]], you need to flip at least 2 ones to make it well-isolated.

Input & Output

example_1.py β€” Small Connected Component
$ Input: grid = [[1,1,0],[0,1,1],[0,0,1]]
β€Ί Output: 2
πŸ’‘ Note: The 1s form connected components. We need to flip 2 positions to make all 1s isolated: flip (0,1) and (1,2) to get [[1,0,0],[0,1,0],[0,0,1]] which is well-isolated.
example_2.py β€” Already Well-Isolated
$ Input: grid = [[1,0,0],[0,0,0],[0,0,1]]
β€Ί Output: 0
πŸ’‘ Note: The matrix is already well-isolated since no 1 is adjacent to another 1. No operations needed.
example_3.py β€” Large Connected Component
$ Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
β€Ί Output: 3
πŸ’‘ Note: This forms a large connected component around the center 0. Using minimum vertex cover approach, we need to remove 3 strategically placed 1s to break all connections.

Time & Space Complexity

Time Complexity
⏱️
O(m*n + k^2.5)

O(m*n) to scan matrix and find components, O(k^2.5) for maximum matching where k is number of 1s

n
2n
βœ“ Linear Growth
Space Complexity
O(m*n)

Space for graph representation and matching algorithm data structures

n
2n
⚑ Linearithmic Space

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≀ m, n ≀ 15
  • grid[i][j] is either 0 or 1
  • The number of 1s in the grid is at most 20
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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