Skip to content

Commit 91d1209

Browse files
authored
Create 1345-jump-game-iv.js
1 parent c43db42 commit 91d1209

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

1345-jump-game-iv.js

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @param {number[]} arr
3+
* @return {number}
4+
*/
5+
var minJumps = function (arr) {
6+
if (arr.length === 1) return 0
7+
const n = arr.length
8+
const indexMap = new Map()
9+
for (let i = n - 1; i >= 0; i--) {
10+
if (!indexMap.has(arr[i])) {
11+
indexMap.set(arr[i], [])
12+
}
13+
indexMap.get(arr[i]).push(i)
14+
}
15+
let distance = 0
16+
const queue = [0, null]
17+
const visited = new Set([0])
18+
while (queue.length > 0) {
19+
const index = queue.shift()
20+
if (index !== null) {
21+
if (index > 0 && !visited.has(index - 1)) {
22+
visited.add(index - 1)
23+
queue.push(index - 1)
24+
}
25+
if (index < n - 1 && !visited.has(index + 1)) {
26+
if (index + 1 === n - 1) return distance + 1
27+
visited.add(index + 1)
28+
queue.push(index + 1)
29+
}
30+
for (const nb of indexMap.get(arr[index])) {
31+
if (!visited.has(nb) && nb !== index - 1 && nb !== index + 1) {
32+
if (nb === n - 1) return distance + 1
33+
visited.add(nb)
34+
queue.push(nb)
35+
}
36+
}
37+
} else {
38+
distance++
39+
if (queue.length > 0) {
40+
queue.push(null)
41+
}
42+
}
43+
}
44+
return -1
45+
}

0 commit comments

Comments
 (0)