LeetCode 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix

Description

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.length
  • n == mat[i].length
  • 1 <= m, n <= 3
  • mat[i][j] is either 0 or 1.

Solutions

Solution 1

PythonJavaC++Go
class Solution: def minFlips(self, mat: List[List[int]]) -> int: m, n = len(mat), len(mat[0]) state = sum(1 << (i * n + j) for i in range(m) for j in range(n) if mat[i][j]) q = deque([state]) vis = {state} ans = 0 dirs = [0, -1, 0, 1, 0, 0] while q: for _ in range(len(q)): state = q.popleft() if state == 0: return ans for i in range(m): for j in range(n): nxt = state for k in range(5): x, y = i + dirs[k], j + dirs[k + 1] if not 0 <= x < m or not 0 <= y < n: continue if nxt & (1 << (x * n + y)): nxt -= 1 << (x * n + y) else: nxt |= 1 << (x * n + y) if nxt not in vis: vis.add(nxt) q.append(nxt) ans += 1 return -1(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !