#1284
Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
HardArrayHash TableBit ManipulationBreadth-First SearchMatrixBreadth-First SearchState Transition
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(2^(m*n)) | O(2^(m*n)) |
| Space | O(1) | O(2^(m*n)) |
💡
Intuition
Time O(2^(m*n))Space O(2^(m*n))
The optimal solution uses a breadth-first search (BFS) to explore the matrix states efficiently. By treating each state as a node and each flip as an edge, we can find the shortest path to the zero matrix without exploring all combinations.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a queue for BFS and a set to track visited states.
- 2Step 2: Start from the initial matrix state and enqueue it with a step count of 0.
- 3Step 3: For each state, generate new states by flipping each cell and its neighbors, enqueueing new states if they haven't been visited.
- 4Step 4: If a new state is the zero matrix, return the step count.
solution.py28 lines
1from collections import deque
2
3def minFlips(mat):
4 m, n = len(mat), len(mat[0])
5 target = tuple([0] * (m * n))
6 start = tuple(cell for row in mat for cell in row)
7 if start == target:
8 return 0
9 queue = deque([(start, 0)])
10 visited = set([start])
11 directions = [(0, 0), (0, 1), (1, 0), (0, -1), (-1, 0)]
12
13 while queue:
14 current, steps = queue.popleft()
15 for i in range(m):
16 for j in range(n):
17 new_state = list(current)
18 for dx, dy in directions:
19 x, y = i + dx, j + dy
20 if 0 <= x < m and 0 <= y < n:
21 new_state[x * n + y] ^= 1
22 new_state = tuple(new_state)
23 if new_state == target:
24 return steps + 1
25 if new_state not in visited:
26 visited.add(new_state)
27 queue.append((new_state, steps + 1))
28 return -1ℹ
Complexity note: The BFS explores all possible states, leading to an exponential number of states. The space complexity is also exponential due to the storage of visited states.
- 1Flipping a cell affects its neighbors, creating complex interactions.
- 2The problem can be viewed as a state transition problem, suitable for BFS.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.