Minimum Number of Flips to Convert Binary Matrix to Zero Matrix - Problem
You are given an m x n binary matrix where each cell is either 0 or 1. Your goal is to transform this entire matrix into a zero matrix (all cells equal to 0) using the minimum number of flip operations.
What is a flip operation? When you flip a cell at position (i, j), you toggle:
- The cell itself: 0 → 1 or 1 → 0
- All four adjacent neighbors (up, down, left, right) that exist within the matrix bounds
For example, flipping the center cell of a 3x3 matrix would affect the center cell plus its 4 neighbors in a cross pattern.
Challenge: Find the minimum number of flips needed to make all cells 0, or return -1 if it's impossible.
This is like playing a lights-out puzzle where pressing a button affects multiple lights at once!
Input & Output
example_1.py — Basic 2x2 Matrix
$
Input:
mat = [[0,0],[0,1]]
›
Output:
3
💡 Note:
One optimal solution: flip (1,0) then (0,0) then (1,1). After first flip: [[1,0],[1,1]], after second flip: [[0,0],[0,1]], after third flip: [[0,0],[0,0]].
example_2.py — Already Zero Matrix
$
Input:
mat = [[0,0],[0,0]]
›
Output:
0
💡 Note:
The matrix is already all zeros, so no flips are needed.
example_3.py — Impossible Case
$
Input:
mat = [[1,0,0],[1,0,0]]
›
Output:
-1
💡 Note:
It's impossible to make this matrix all zeros no matter how many flips we perform, so return -1.
Constraints
-
m == mat.length -
n == mat[0].length -
1 <= m, n <= 3 -
mat[i][j]is either0or1
Visualization
Tap to expand
Understanding the Visualization
1
Initial State
Start with the given binary matrix - this is our initial state
2
Generate Moves
From current state, we can flip any cell, creating new possible states
3
BFS Exploration
Use BFS to systematically explore states level by level
4
Target Found
When we reach the zero matrix state, we've found the minimum flips
Key Takeaway
🎯 Key Insight: Use BFS to explore matrix states systematically - each flip creates a new state, and BFS guarantees we find the minimum number of flips by exploring states level by level until we reach the zero matrix.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code