-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.java
81 lines (78 loc) · 2.73 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
class Solution {
private int n;
private int[][] g;
private int[][][] res;
private int[][][] degree;
private static final int HOLE = 0, MOUSE_START = 1, CAT_START = 2;
private static final int MOUSE_TURN = 0, CAT_TURN = 1;
private static final int MOUSE_WIN = 1, CAT_WIN = 2, TIE = 0;
public int catMouseGame(int[][] graph) {
n = graph.length;
g = graph;
res = new int[n][n][2];
degree = new int[n][n][2];
for (int i = 0; i < n; ++i) {
for (int j = 1; j < n; ++j) {
degree[i][j][MOUSE_TURN] = g[i].length;
degree[i][j][CAT_TURN] = g[j].length;
}
}
for (int i = 0; i < n; ++i) {
for (int j : g[HOLE]) {
--degree[i][j][CAT_TURN];
}
}
Deque<int[]> q = new ArrayDeque<>();
for (int j = 1; j < n; ++j) {
res[0][j][MOUSE_TURN] = MOUSE_WIN;
res[0][j][CAT_TURN] = MOUSE_WIN;
q.offer(new int[] {0, j, MOUSE_TURN});
q.offer(new int[] {0, j, CAT_TURN});
}
for (int i = 1; i < n; ++i) {
res[i][i][MOUSE_TURN] = CAT_WIN;
res[i][i][CAT_TURN] = CAT_WIN;
q.offer(new int[] {i, i, MOUSE_TURN});
q.offer(new int[] {i, i, CAT_TURN});
}
while (!q.isEmpty()) {
int[] state = q.poll();
int t = res[state[0]][state[1]][state[2]];
List<int[]> prevStates = getPrevStates(state);
for (var prevState : prevStates) {
int pm = prevState[0], pc = prevState[1], pt = prevState[2];
if (res[pm][pc][pt] == TIE) {
boolean win
= (t == MOUSE_WIN && pt == MOUSE_TURN) || (t == CAT_WIN && pt == CAT_TURN);
if (win) {
res[pm][pc][pt] = t;
q.offer(prevState);
} else {
if (--degree[pm][pc][pt] == 0) {
res[pm][pc][pt] = t;
q.offer(prevState);
}
}
}
}
}
return res[MOUSE_START][CAT_START][MOUSE_TURN];
}
private List<int[]> getPrevStates(int[] state) {
List<int[]> pre = new ArrayList<>();
int m = state[0], c = state[1], t = state[2];
int pt = t ^ 1;
if (pt == CAT_TURN) {
for (int pc : g[c]) {
if (pc != HOLE) {
pre.add(new int[] {m, pc, pt});
}
}
} else {
for (int pm : g[m]) {
pre.add(new int[] {pm, c, pt});
}
}
return pre;
}
}