Minimum Number of Flips to Convert Binary Matrix to Zero Matrix Problem
Description
LeetCode Problem 1284.
Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighbors if they share one edge.
Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.
A binary matrix is a matrix with all cells equal to 0 or 1 only.
A zero matrix is a matrix with all cells equal to 0.
Example 1:

Input: mat = [[0,0],[0,1]]
Output: 3
Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.
Example 2:
Input: mat = [[0]]
Output: 0
Explanation: Given matrix is a zero matrix. We do not need to change it.
Example 3:
Input: mat = [[1,0,0],[1,0,0]]
Output: -1
Explanation: Given matrix cannot be a zero matrix.
Constraints:
m == mat.lengthn == mat[i].length1 <= m, n <= 3mat[i][j]is either0or1.
Solution
Approach: BFS over Bitmask States
The matrix has at most 3 x 3 = 9 cells, so it has at most 29 = 512 possible states. Pack a state into one integer: cell (i, j) is bit i * n + j. Flipping cell (i, j) toggles that cell and its existing neighbours, which is the same as XOR-ing the state with a fixed mask. We build the m * n masks once.
Now the question is a shortest path in a graph: the nodes are the states, each of the m * n flips is an edge, and we want the distance from the starting state to 0. Breadth-first search finds it, and if 0 is never reached the answer is -1 (as in Example 3).
Two facts explain why the numbers stay small. Flipping the same cell twice cancels out, and the order of the flips does not matter (XOR is commutative), so an optimal answer flips each cell at most once and is at most m * n. BFS discovers this on its own; we only need the visited set so that no state is expanded twice.
Complexity: O(2mn · mn) time and O(2mn) space, at most 512 · 9 steps here.
from collections import deque
class Solution:
def minFlips(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
# Cell (i, j) is bit i * n + j; flipping it XORs the cell and its neighbours.
moves = []
for i in range(m):
for j in range(n):
mask = 0
for x, y in ((i, j), (i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
if 0 <= x < m and 0 <= y < n:
mask |= 1 << (x * n + y)
moves.append(mask)
start = sum(1 << (i * n + j) for i in range(m) for j in range(n) if mat[i][j])
dist = {start: 0}
q = deque([start])
while q:
state = q.popleft()
if state == 0:
return dist[state]
for mask in moves:
nxt = state ^ mask
if nxt not in dist:
dist[nxt] = dist[state] + 1
q.append(nxt)
return -1