forked from ex01tus/leetcode-grind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJumpGame3.java
More file actions
25 lines (20 loc) · 712 Bytes
/
JumpGame3.java
File metadata and controls
25 lines (20 loc) · 712 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
package graph;
/**
* Description: https://leetcode.com/problems/jump-game-iii
* Difficulty: Medium
* Time complexity: O(n)
* Space complexity: O(1)
*/
public class JumpGame3 {
public boolean canReach(int[] arr, int start) {
return canReach(arr, start, new int[arr.length]);
}
private boolean canReach(int[] arr, int start, int[] visited) {
if (start < 0 || start >= arr.length || visited[start] == 1) return false;
if (arr[start] == 0) return true;
visited[start] = 1;
boolean jumpRight = canReach(arr, start + arr[start], visited);
boolean jumpLeft = canReach(arr, start - arr[start], visited);
return jumpRight || jumpLeft;
}
}