LeetCode 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
题目:
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 either0
or1
.
题解:
The quesiton asks for the minimum number of steps to cover to all 0.
The minimum steps is related to BFS.
In BFS queue, we maintain the current state of matrix.
We can use a integer and bit representation for each state.
If current state == 0, we find the result and return level.
Otherwise, for each (i, j) coordiante, we check all 5 dir, if it is within bound, we flip the value, and get the next. If next is not visited before, add to the queue.
Time Complexity: O(2 ^ (m * n)). m = matrix.length. n = matrix[0].length. There could be 2 ^ (m * n) states.
Space: O(2 ^ (m * n))
AC Java:
1 class Solution { 2 int[][] dirs = new int[][]{{0, 0}, {0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 3 public int minFlips(int[][] mat) { 4 int m = mat.length; 5 int n = mat[0].length; 6 int state = 0; 7 for(int i = 0; i < m; i++){ 8 for(int j = 0; j < n; j++){ 9 state |= (mat[i][j] << (i * n + j)); 10 } 11 } 12 13 HashSet<Integer> visited = new HashSet<>(); 14 LinkedList<Integer> que = new LinkedList<>(); 15 visited.add(state); 16 que.add(state); 17 int level = 0; 18 19 while(!que.isEmpty()){ 20 int size = que.size(); 21 while(size-- > 0){ 22 int cur = que.poll(); 23 if(cur == 0){ 24 return level; 25 } 26 27 for(int i = 0; i < m; i++){ 28 for(int j = 0; j < n; j++){ 29 int next = cur; 30 for(int [] dir : dirs){ 31 int x = i + dir[0]; 32 int y = j + dir[1]; 33 if(x >= 0 && x < m && y >= 0 && y < n){ 34 next ^= (1 << (x * n + y)); 35 } 36 } 37 38 if(!visited.contains(next)){ 39 visited.add(next); 40 que.add(next); 41 } 42 } 43 } 44 } 45 46 level++; 47 } 48 49 return -1; 50 } 51 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】博客园2025新款「AI繁忙」系列T恤上架,前往周边小店选购
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步