-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1306.jump-game-iii.java
75 lines (64 loc) · 1.93 KB
/
1306.jump-game-iii.java
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.util.LinkedList;
import java.util.Queue;
/*
* @lc app=leetcode id=1306 lang=java
*
* [1306] Jump Game III
*/
// @lc code=start
// class Solution {
// boolean[] visited;
// public boolean canReach(int[] arr, int start) {
// int n = arr.length;
// visited = new boolean[n];
// Queue<Integer> q = new LinkedList<>();
// visited[start] = true;
// q.add(start);
// while (!q.isEmpty()) {
// int currIdx = q.poll();
// // check if you can reach to any index with value 0
// if (arr[currIdx] == 0) {
// return true;
// }
// int lNextIdx = currIdx - arr[currIdx];
// int rNextIdx = currIdx + arr[currIdx];
// if (0 <= lNextIdx && lNextIdx < n && !visited[lNextIdx]) {
// visited[lNextIdx] = true;
// q.add(lNextIdx);
// }
// if (0 <= rNextIdx && rNextIdx < n && !visited[rNextIdx]) {
// visited[rNextIdx] = true;
// q.add(rNextIdx);
// }
// }
// return false;
// }
// }
class Solution {
int n;
boolean[] visited;
public boolean canReach(int[] arr, int start) {
n = arr.length;
visited = new boolean[n];
return dfs(arr, start);
}
public boolean dfs(int[] arr, int currIdx) {
if (arr[currIdx] == 0) {
return true;
}
int lNextIdx = currIdx - arr[currIdx];
int rNextIdx = currIdx + arr[currIdx];
if (0 <= lNextIdx && lNextIdx < n && !visited[lNextIdx]) {
visited[lNextIdx] = true;
if (dfs(arr, lNextIdx))
return true;
}
if (0 <= rNextIdx && rNextIdx < n && !visited[rNextIdx]) {
visited[rNextIdx] = true;
if (dfs(arr, rNextIdx))
return true;
}
return false;
}
}
// @lc code=end