-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy path1345-Jump-Game-IV.js
More file actions
43 lines (36 loc) · 875 Bytes
/
1345-Jump-Game-IV.js
File metadata and controls
43 lines (36 loc) · 875 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* @param {number[]} arr
* @return {number}
*/
const minJumps = (arr) => {
if (!arr || arr.length <= 1) return 0;
let len = arr.length;
let map = {};
let dp = new Array(len).fill(-1);
for (let i = 0; i < len; i++) {
if (!map[arr[i]]) {
map[arr[i]] = [];
}
map[arr[i]].push(i);
}
let queue = [0];
dp[0] = 0;
while (queue.length) {
let i = queue.pop();
let next = [];
if (i > 0) next.push(i - 1);
if (i < len - 1) next.push(i + 1);
if (map[arr[i]]) {
for (let idx of map[arr[i]]) {
next.push(idx);
}
}
map[arr[i]] = null;
for (let t of next) {
if (dp[t] !== -1) continue;
dp[t] = dp[i] + 1;
queue.unshift(t);
}
}
return dp[len - 1];
};