-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy path1306-jump-game-iii.js
More file actions
41 lines (38 loc) · 815 Bytes
/
1306-jump-game-iii.js
File metadata and controls
41 lines (38 loc) · 815 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
/**
* @param {number[]} arr
* @param {number} start
* @return {boolean}
*/
var canReach = function(arr, start) {
const explored = new Set()
function dfs(i) {
if(i<0 || i>=arr.length) return false
if(arr[i]===0) return true
if(explored.has(i)) return false
explored.add(i)
return dfs(i-arr[i]) || dfs(i+arr[i])
}
return dfs(start)
};
/**
* @param {number[]} arr
* @param {number} start
* @return {boolean}
*/
var canReachIter = function(arr, start) {
let ind
let elem
const s = [start]
const explored = new Set()
while(s.length>0) {
ind = s.pop()
if(ind<0 || ind>=arr.length) continue
elem = arr[ind]
if(elem === 0) return true
if(explored.has(ind)) continue
explored.add(ind)
s.push(ind-elem)
s.push(ind+elem)
}
return false
};