Remove All Ones With Row and Column Flips II Problem
Description
LeetCode Problem 2174.
You are given a 0-indexed m x n binary matrix grid.
In one operation, you can choose any i and j that meet the following conditions:
0 <= i < m0 <= j < ngrid[i][j] == 1
and change the values of all cells in row i and column j to zero.
Return the minimum number of operations needed to remove all 1's from grid.
Example 1:

Input: grid = [[1,1,1],[1,1,1],[0,1,0]]
Output: 2
Explanation:
In the first operation, change all cell values of row 1 and column 1 to zero.
In the second operation, change all cell values of row 0 and column 0 to zero.
Example 2:

Input: grid = [[0,1,0],[1,0,1],[0,1,0]]
Output: 2
Explanation:
In the first operation, change all cell values of row 1 and column 0 to zero.
In the second operation, change all cell values of row 2 and column 1 to zero.
Note that we cannot perform an operation using row 1 and column 1 because grid[1][1] != 1.
Example 3:

Input: grid = [[0,0],[0,0]]
Output: 0
Explanation:
There are no 1's to remove so return 0.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 151 <= m * n <= 15grid[i][j]is either0or1.
Solution
Approach: BFS over bitmasks
The grid has at most 15 cells, so the whole grid fits in a bitmask state with one bit per cell. An operation picks a cell that is currently 1 and clears its entire row and column in the mask.
Run a BFS from the initial mask. From each mask, try every cell whose bit is set, compute the mask with that cell's row and column cleared, and enqueue it if it has not been seen. The number of BFS levels needed to reach mask 0 is the answer.
Complexity: time O(2^(m*n) * m * n * (m + n)) in the worst case, space O(2^(m*n)).
from collections import deque
class Solution:
def removeOnes(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
state = sum(1 << (i * n + j) for i in range(m) for j in range(n) if grid[i][j])
q = deque([state])
vis = {state}
ans = 0
while q:
for _ in range(len(q)):
state = q.popleft()
if state == 0:
return ans
for i in range(m):
for j in range(n):
if not (state >> (i * n + j)) & 1:
continue
nxt = state
for r in range(m):
nxt &= ~(1 << (r * n + j))
for c in range(n):
nxt &= ~(1 << (i * n + c))
if nxt not in vis:
vis.add(nxt)
q.append(nxt)
ans += 1
return -1