Skip to content

Commit e8cf1ff

Browse files
authored
Create 1728-cat-and-mouse-ii.js
1 parent d179b02 commit e8cf1ff

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

1728-cat-and-mouse-ii.js

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/**
2+
* @param {string[]} grid
3+
* @param {number} catJump
4+
* @param {number} mouseJump
5+
* @return {boolean}
6+
*/
7+
const canMouseWin = function(grid, catJump, mouseJump) {
8+
let n,m,k,lim,cache,mpos = -1, cpos = -1, fpos = -1
9+
n = grid.length
10+
m = grid[0].length
11+
for(let i = 0; i < n; i++) {
12+
for(let j = 0; j < m; j++) {
13+
if(grid[i][j] === 'M') mpos = i * m + j
14+
else if(grid[i][j] === 'C') cpos = i * m + j
15+
else if(grid[i][j] === 'F') fpos = i * m + j
16+
}
17+
}
18+
mnei = Array(n * m), cnei = Array(n * m)
19+
for(let i = 0; i < n; i++) {
20+
for(let j = 0; j < m; j++) {
21+
mnei[i * m + j] = traj(i, j, mouseJump)
22+
}
23+
}
24+
for(let i = 0; i < n; i++) {
25+
for(let j = 0; j < m; j++) {
26+
cnei[i * m + j] = traj(i, j, catJump)
27+
}
28+
}
29+
k = m * n
30+
lim = 100
31+
cache = Array.from({ length: lim }, () => Array(k * k).fill(0))
32+
33+
for(let i = 0; i < lim; i++) {
34+
for(let j = 0; j < k * k; j++) {
35+
cache[i][j] = -1
36+
}
37+
}
38+
39+
return mouseWin(mpos, cpos, 0)
40+
41+
function traj(i, j, d) {
42+
if(grid[i][j] === '#') return []
43+
let pos = i * m + j
44+
let change = []
45+
change.push(pos)
46+
for(let k = 1; k < d + 1; k++) {
47+
if(i + k >= n || grid[i + k][j] === '#') break
48+
change.push(pos + k * m)
49+
}
50+
for(let k = 1; k < d + 1; k++) {
51+
if(i - k < 0 || grid[i - k][j] === '#') break
52+
change.push(pos - k * m)
53+
}
54+
for(let k = 1; k < d + 1; k++) {
55+
if(j + k >= m || grid[i][j + k] === '#') break
56+
change.push(pos + k)
57+
}
58+
for(let k = 1; k < d + 1; k++) {
59+
if(j - k < 0 || grid[i][j - k] === '#') break
60+
change.push(pos - k)
61+
}
62+
return change
63+
}
64+
65+
function mouseWin(mpos, cpos, turn) {
66+
if(turn === lim) return false
67+
let e = mpos * k + cpos
68+
if(cache[turn][e] >= 0) return cache[turn][e] === 1
69+
if(cpos === fpos || cpos === mpos) return false
70+
if(mpos === fpos) return true
71+
if((turn & 1) !== 0) {
72+
let b = 0
73+
for(let newCpos of cnei[cpos]) {
74+
if(!mouseWin(mpos, newCpos, turn + 1)) b = 1
75+
}
76+
if(b===0) cache[turn][e] = 1
77+
else cache[turn][e] = 0
78+
} else {
79+
let b = 0
80+
for(let newMpos of mnei[mpos]) {
81+
if(mouseWin(newMpos, cpos, turn + 1)) b = 1
82+
}
83+
if(b === 1) cache[turn][e] = 1
84+
else cache[turn][e] = 0
85+
}
86+
return cache[turn][e] === 1
87+
}
88+
};

0 commit comments

Comments
 (0)