-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy path1306-jump-game-iii.js
39 lines (32 loc) · 973 Bytes
/
1306-jump-game-iii.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
/**
* 1306. Jump Game III
* https://leetcode.com/problems/jump-game-iii/
* Difficulty: Medium
*
* Given an array of non-negative integers arr, you are initially positioned at start index of
* the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you
* can reach any index with value 0.
*
* Notice that you can not jump outside of the array at any time.
*/
/**
* @param {number[]} arr
* @param {number} start
* @return {boolean}
*/
var canReach = function(arr, start) {
const visited = new Set();
const queue = [start];
while (queue.length) {
const current = queue.shift();
if (arr[current] === 0) return true;
if (visited.has(current)) continue;
visited.add(current);
const jump = arr[current];
const nextRight = current + jump;
const nextLeft = current - jump;
if (nextRight < arr.length) queue.push(nextRight);
if (nextLeft >= 0) queue.push(nextLeft);
}
return false;
};