-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
49 lines (49 loc) · 1.64 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
public int minFlips(int[][] mat) {
int m = mat.length, n = mat[0].length;
int state = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (mat[i][j] == 1) {
state |= 1 << (i * n + j);
}
}
}
Deque<Integer> q = new ArrayDeque<>();
q.offer(state);
Set<Integer> vis = new HashSet<>();
vis.add(state);
int ans = 0;
int[] dirs = {0, -1, 0, 1, 0, 0};
while (!q.isEmpty()) {
for (int t = q.size(); t > 0; --t) {
state = q.poll();
if (state == 0) {
return ans;
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int nxt = state;
for (int k = 0; k < 5; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x < 0 || x >= m || y < 0 || y >= n) {
continue;
}
if ((nxt & (1 << (x * n + y))) != 0) {
nxt -= 1 << (x * n + y);
} else {
nxt |= 1 << (x * n + y);
}
}
if (!vis.contains(nxt)) {
vis.add(nxt);
q.offer(nxt);
}
}
}
}
++ans;
}
return -1;
}
}