Cat and Mouse LeetCode solution in JavaScript

1
var catMouseGame = function (graph) {
2
let n = graph.length,
3
memo = [...Array(n + 1)].map((d) =>
4
[...Array(n + 1)].map((d) => [...Array(2 * n + 1)])
5
),
6
seen = [...Array(n + 1)].map((d) =>
7
[...Array(n + 1)].map((d) => [...Array(2)])
8
);
9
//dfs returns 0 1 2, whether the current player loses,wins, or draws respectively
10
let dfs = (M, C, level) => {
11
let turn = level % 2,
12
curr = turn ? C : M,
13
draw = 0,
14
res = 0;
15
//draw when we ve seen the state before or cycles
16
if (seen[M][C][turn] !== undefined || level >= 2 * n)
17
return (memo[M][C][level] = 2);
18
if (M == 0)
19
// win for mouse if it reaches the hole, loss for cat
20
memo[M][C][level] = turn ^ 1;
21
if (M == C)
22
// win for cat if it reaches the mouse, loss for mouse
23
memo[M][C][level] = turn;
24
if (memo[M][C][level] === undefined) {
25
seen[M][C][turn] = 0; //set this state as visited
26
for (
27
let i = 0;
28
i < graph[curr].length && !res;
29
i++ //traverse for the available edges
30
)
31
if (!(turn && !graph[curr][i])) {
32
//The cat cant move into the hole
33
let val = turn
34
? dfs(M, graph[curr][i], level + 1)
35
: dfs(graph[curr][i], C, level + 1);
36
if (val === 2)
37
draw = 1; //set draw as an available option
38
else res |= 1 ^ val; //minimax logic, always prefer the losing state of the opponent
39
}
40
memo[M][C][level] = res || 2 * draw; // set in this order 1->2->0
41
}
42
seen[M][C][turn] = undefined; // de-set the state for the current game,as it concluded
43
return memo[M][C][level];
44
};
45
return [2, 1, 0][dfs(1, 2, 0)]; //js eye candy
46
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0