-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathJumpGameIII.java
More file actions
34 lines (30 loc) · 1 KB
/
JumpGameIII.java
File metadata and controls
34 lines (30 loc) · 1 KB
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
class JumpGameIII {
public boolean canReach(int[] arr, int start) {
// O(n) : TC
// O(n) : SC boolean array
Queue<Integer> qu = new LinkedList<>();
boolean[] visited = new boolean[arr.length];
qu.offer(start);
while(!qu.isEmpty()){
int size = qu.size();
while(size-->0){
Integer head = qu.poll();
if(arr[head] == 0){
return true;
}
if(!visited[head]){
int forwardIndex = head + arr[head];
if(forwardIndex>=0 && forwardIndex <arr.length){
qu.offer(forwardIndex);
}
int backwardIndex = head - arr[head];
if(backwardIndex>=0 && backwardIndex <arr.length){
qu.offer(backwardIndex);
}
visited[head] = true;
}
}
}
return false;
}
}