-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJump Game IV.js
45 lines (42 loc) · 1.15 KB
/
Jump Game IV.js
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
44
45
/**
* @param {number[]} arr
* @return {number}
*/
var minJumps = function(arr) {
const map = {};
const visited = Array(arr.length).fill(false);
for (let i = 0; i < arr.length; i++) {
if (!map[arr[i]]) {
map[arr[i]] = [i];
} else {
map[arr[i]].push(i);
}
}
const q = [[arr.length - 1, 0]];
visited[arr.length - 1] = true;
while (q.length) {
let [idx, length] = q.shift();
if (idx === 0) {
return length;
}
length++;
if (idx + 1 < arr.length && !visited[idx + 1]) {
visited[idx + 1] = true;
q.push([idx + 1, length]);
}
if (idx - 1 >= 0 && !visited[idx - 1]) {
visited[idx - 1] = true;
q.push([idx - 1, length]);
}
if (map[arr[idx]]) {
while (map[arr[idx]].length) {
const index = map[arr[idx]].pop();
if (index === idx || visited[index]) {
continue;
}
visited[index] = true;
q.push([index, length]);
}
}
}
};