forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJump Game IV.js
57 lines (43 loc) · 1.32 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
46
47
48
49
50
51
52
53
54
55
56
57
/**
* @param {number[]} arr
* @return {number}
*/
var minJumps = function(arr) {
if(arr.length <= 1) return 0;
const graph = {};
for(let idx = 0; idx < arr.length; idx ++) {
const num = arr[idx];
if(graph[num] === undefined) graph[num] = [];
graph[num].push(idx);
}
let queue = [];
const visited = new Set();
queue.push(0);
visited.add(0);
let steps = 0;
while(queue.length) {
const nextQueue = [];
for(const idx of queue) {
if(idx === arr.length - 1) return steps;
const num = arr[idx];
for(const neighbor of graph[num]) {
if(!visited.has(neighbor)) {
visited.add(neighbor);
nextQueue.push(neighbor);
}
}
if(idx + 1 < arr.length && !visited.has(idx + 1)) {
visited.add(idx + 1);
nextQueue.push(idx + 1);
}
if(idx - 1 >= 0 && !visited.has(idx - 1)) {
visited.add(idx - 1);
nextQueue.push(idx - 1);
}
graph[num].length = 0;
}
queue = nextQueue;
steps ++;
}
return -1;
};