forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcat-and-mouse.cpp
66 lines (61 loc) · 2.02 KB
/
cat-and-mouse.cpp
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
// Time: O(n^3)
// Space: O(n^2)
class Solution {
private:
template <typename A, typename B, typename C>
struct TupleHash {
size_t operator()(const tuple<A, B, C>& p) const {
size_t seed = 0;
A a; B b; C c;
tie(a, b, c) = p;
seed ^= std::hash<A>{}(a) + 0x9e3779b9 + (seed<<6) + (seed>>2);
seed ^= std::hash<B>{}(b) + 0x9e3779b9 + (seed<<6) + (seed>>2);
seed ^= std::hash<C>{}(c) + 0x9e3779b9 + (seed<<6) + (seed>>2);
return seed;
}
};
using Lookup = unordered_map<tuple<int, int, bool>, int, TupleHash<int, int, bool>>;
public:
int catMouseGame(vector<vector<int>>& graph) {
Lookup lookup;
return move(graph, &lookup, MOUSE_START, CAT_START, true);
}
private:
enum Location {HOLE, MOUSE_START, CAT_START};
enum Result {DRAW, MOUSE, CAT};
int move(const vector<vector<int>>& graph, Lookup *lookup, int i, int other_i, bool is_mouse_turn) {
const auto& key = make_tuple(i, other_i, is_mouse_turn);
if (lookup->count(key)) {
return (*lookup)[key];
}
(*lookup)[key] = DRAW;
int skip, target, win, lose;
if (is_mouse_turn) {
tie(skip, target, win, lose) = make_tuple(other_i, HOLE, MOUSE, CAT);
} else {
tie(skip, target, win, lose) = make_tuple(HOLE, other_i, CAT, MOUSE);
}
for (const auto& nei : graph[i]) {
if (nei == target) {
(*lookup)[key] = win;
return win;
}
}
int result = lose;
for (const auto& nei : graph[i]) {
if (nei == skip) {
continue;
}
auto tmp = move(graph, lookup, other_i, nei, !is_mouse_turn);
if (tmp == win) {
result = win;
break;
}
if (tmp == DRAW) {
result = DRAW;
}
}
(*lookup)[key] = result;
return result;
}
};