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 either 0 or 1

Visualization

Tap to expand
Binary Matrix Flip State SpaceInitial State1001After 1 FlipAfter 2 FlipsTarget: All Zeros!0000BFS Level-by-Level ExplorationEach level represents states reachable in exactly k flipsFirst time we reach zero matrix = minimum flips neededKey Insight: Flip Effectsโ€ข Flipping cell (i,j) toggles itself + 4 neighbors (cross pattern)โ€ข Order of flips doesn't matter: Aโ†’Bโ†’C same as Cโ†’Aโ†’Bโ€ข Each cell should be flipped at most once in optimal solution
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.
Asked in
Google 45 Facebook 32 Amazon 28 Microsoft 19
23.4K Views
Medium Frequency
~25 min Avg. Time
892 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