Skip to content

Commit b46ff3f

Browse files
authored
Create 864-shortest-path-to-get-all-keys.js
1 parent f0398d7 commit b46ff3f

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

864-shortest-path-to-get-all-keys.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* @param {string[]} grid
3+
* @return {number}
4+
*/
5+
const shortestPathAllKeys = function(grid) {
6+
let r = grid.length,
7+
c = grid[0].length
8+
let moves = [[-1, 0], [1, 0], [0, 1], [0, -1]]
9+
let finalState = 0,
10+
startPoint = null
11+
for (let i = 0; i < r; i++) {
12+
for (let j = 0; j < c; j++) {
13+
let code = grid[i].charCodeAt(j) - 97
14+
if (code >= 0 && code <= 5) {
15+
finalState = finalState | (1 << code)
16+
} else if (grid[i][j] === '@') {
17+
startPoint = [i, j]
18+
}
19+
}
20+
}
21+
let visited = Array(finalState + 1)
22+
.fill()
23+
.map(() =>
24+
Array(r)
25+
.fill()
26+
.map(() => Array(c).fill(false))
27+
)
28+
let step = 0
29+
let arr = [[startPoint[0], startPoint[1], 0]]
30+
while (arr.length > 0) {
31+
let len = arr.length
32+
for (let i = 0; i < len; i++) {
33+
let [x, y, keysState] = arr.shift()
34+
for (let [dx, dy] of moves) {
35+
let newx = x + dx,
36+
newy = y + dy
37+
if (newx < 0 || newy < 0 || newx >= r || newy >= c) continue
38+
let curstr = grid[newx][newy]
39+
if (curstr === '#') continue
40+
let code = grid[newx].charCodeAt(newy)
41+
if (visited[keysState][newx][newy]) continue
42+
visited[keysState][newx][newy] = true
43+
if (code >= 65 && code <= 72 && ((1 << (code - 65)) & keysState) === 0)
44+
continue
45+
let newState = keysState
46+
if (
47+
code >= 97 &&
48+
code <= 102 &&
49+
((1 << (code - 97)) & keysState) === 0
50+
) {
51+
newState = newState | (1 << (code - 97))
52+
if (newState === finalState) return step + 1
53+
}
54+
arr.push([newx, newy, newState])
55+
}
56+
}
57+
step++
58+
}
59+
return -1
60+
}

0 commit comments

Comments
 (0)