Minimum Number of Flips to Convert Binary Matrix to Zero Matrix

Given an m x n binary matrix mat. In one step, you can choose one cell and flip it and all four neighbors of it if they exist. A flip changes 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
0 0
0 1
Inputmat = [[0,0],[0,1]]
Output3
One possible solution is to flip (1, 0), then (0, 1), and finally (1, 1).
Example 2
0
Inputmat = [[0]]
Output0
The given matrix is already a zero matrix, so no changes are needed.

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 3
  • mat[i][j] is either 0 or 1.

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate