[LeetCode] Cat and Mouse

913. Cat and Mouse

A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.

The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.

The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0.

During each player’s turn, they must travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it must travel to any node in graph[1].

Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)

Then, the game can end in three ways:

  • If ever the Cat occupies the same node as the Mouse, the Cat wins.
  • If ever the Mouse reaches the Hole, the Mouse wins.
  • If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player’s turn to move), the game is a draw.

Given a graph, and assuming both players play optimally, return

  • 1 if the mouse wins the game,
  • 2 if the cat wins the game, or
  • 0 if the game is a draw.
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
class Solution {
int dp[50][50][151];
int solution(vector<vector<int>>& g, int mouse, int cat, int step) {
if(mouse == 0) return 1;
if(mouse == cat) return 2;
if(step == 3 * g.size()) return 0;

if(dp[mouse][cat][step] != -1) return dp[mouse][cat][step];
dp[mouse][cat][step] = 0;
int draw = 0, catWin = 0, mouseWin = 0;
for(auto next : g[step & 1 ? cat : mouse]) {
if(step & 1 and next == 0) continue;
int res = solution(g, step & 1 ? mouse : next, step & 1 ? next : cat, step + 1);

if(step & 1 and res == 2) return dp[mouse][cat][step] = 2;
if(!(step & 1) and res == 1) return dp[mouse][cat][step] = 1;
if(res == 0) draw++;
else if(res == 1) mouseWin++;
else if(res == 2) catWin++;
}
if(!(step & 1)) {
if(mouseWin) dp[mouse][cat][step] = 1;
else if(draw) dp[mouse][cat][step] = 0;
else dp[mouse][cat][step] = 2;
} else {
if(catWin) dp[mouse][cat][step] = 2;
else if(draw) dp[mouse][cat][step] = 0;
else dp[mouse][cat][step] = 1;
}
return dp[mouse][cat][step];
}
public:
int catMouseGame(vector<vector<int>>& graph) {
memset(dp,-1,sizeof(dp));
return solution(graph, 1, 2, 0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/15/PS/LeetCode/cat-and-mouse/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.