HardNo. 1284

Minimum Number of Flips to Convert Binary Matrix to Zero Matrix — LeetCode 1284 Python Solution

Topics
Bit Manipulation, Breadth-First Search, Array, Hash Table, Matrix
Reading time
5 min

The problem

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).

Example

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.

Python solution

PythonSolution
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

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0959Regions Cut By SlashesMedium
2732Find a Good Subset of the MatrixHard
1275Find Winner on a Tic Tac Toe GameEasy
0036Valid SudokuMedium
0037Sudoku SolverHard
0073Set Matrix ZeroesMedium

Frequently asked questions

How hard is LeetCode 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix?

LeetCode 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix is rated Hard on LeetCode.

What is the time complexity of LeetCode 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix cover?

LeetCode 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix is tagged Bit Manipulation, Breadth-First Search, Array, Hash Table and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.