1
var catMouseGame = function (graph) {3
memo = [...Array(n + 1)].map((d) =>4
[...Array(n + 1)].map((d) => [...Array(2 * n + 1)])6
seen = [...Array(n + 1)].map((d) =>7
[...Array(n + 1)].map((d) => [...Array(2)])9
//dfs returns 0 1 2, whether the current player loses,wins, or draws respectively10
let dfs = (M, C, level) => {15
//draw when we ve seen the state before or cycles16
if (seen[M][C][turn] !== undefined || level >= 2 * n)17
return (memo[M][C][level] = 2);19
// win for mouse if it reaches the hole, loss for cat20
memo[M][C][level] = turn ^ 1;22
// win for cat if it reaches the mouse, loss for mouse23
memo[M][C][level] = turn;24
if (memo[M][C][level] === undefined) {25
seen[M][C][turn] = 0; //set this state as visited28
i < graph[curr].length && !res;29
i++ //traverse for the available edges31
if (!(turn && !graph[curr][i])) {32
//The cat cant move into the hole34
? dfs(M, graph[curr][i], level + 1)35
: dfs(graph[curr][i], C, level + 1);37
draw = 1; //set draw as an available option38
else res |= 1 ^ val; //minimax logic, always prefer the losing state of the opponent40
memo[M][C][level] = res || 2 * draw; // set in this order 1->2->042
seen[M][C][turn] = undefined; // de-set the state for the current game,as it concluded43
return memo[M][C][level];45
return [2, 1, 0][dfs(1, 2, 0)]; //js eye candy