Given a m x n
binary matrix mat
. In one step, you can choose one cell and flip it and all the four neighbours of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighboors if they share one edge.
Return the minimum number of steps required to convert mat
to a zero matrix or -1 if you cannot.
Binary matrix is a matrix with all cells equal to 0 or 1 only.
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.
思路:就是BFS,不难,难点就是board的状态表示;用bit位移,来形成个integer;注意flip bit 是next ^= 1 << (i * n + j); 注意,一层是所有的board的点,全部变一次是一层,然后下一层,再所有的点变一次;Time: O(2^mn) Space: O( m*n * sizeof(String (m*n)))
class Solution {
public int minFlips(int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int start = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
start += mat[i][j] << (i * n + j);
}
}
int[][] dirs = new int[][] {{0,1},{0,-1},{-1,0},{1,0}};
Queue<Integer> queue = new LinkedList<>();
HashSet<Integer> visited = new HashSet<>();
queue.offer(start);
visited.add(start);
int step = 0;
while(!queue.isEmpty()) {
int size = queue.size();
for(int k = 0; k < size; k++) {
Integer node = queue.poll();
if(node == 0) {
return step;
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
int next = node;
next ^= 1 << (i * n + j);
for(int[] dir: dirs) {
int nx = i + dir[0];
int ny = j + dir[1];
if(0 <= nx && nx < m && 0 <= ny && ny < n) {
next ^= 1 << (nx * n + ny);
}
}
if(!visited.contains(next)) {
visited.add(next);
queue.offer(next);
}
}
}
}
step++;
}
return -1;
}
}