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 to Zero Matrix - BFS Approach INPUT Binary Matrix (2x2) 0 0 0 1 (0,0) (0,1) (0) (1) Flip Operation: Red=target, Green=affected mat = [[0,0],[0,1]] ALGORITHM STEPS 1 Encode State Matrix --> bitmask integer [[0,0],[0,1]] = 0100 = 4 2 BFS Setup Queue: [(state=4, flips=0)] Target: state = 0 3 Explore Flips Try flipping each cell Add new states to queue 4 ... ... 4 Find Zero State Return flips when state=0 or -1 if impossible Level = min flips needed FINAL RESULT Flip Sequence (3 flips) Initial: 0 0 0 1 Flip(0,0) After 1: 1 1 1 1 After 2: Flip(0,1) 1 0 1 0 After 3: Flip(1,0) 0 0 0 0 ALL ZERO Output 3 Minimum flips = 3 Key Insight: BFS explores states level by level. Each matrix state is encoded as a bitmask (2^(m*n) possible states). The first time we reach state 0 (all zeros) guarantees minimum flips. Each flip toggles specific bits in the bitmask. Time: O(2^(mn) * mn), Space: O(2^(mn)) for visited states. TutorialsPoint - Minimum Number of Flips to Convert Binary Matrix to Zero Matrix | BFS Approach
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