Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public boolean canReach(int[] arr, int start) {
- boolean[] visited = new boolean[arr.length];
- return dfs(arr, start, visited);
- }
- private boolean dfs(int[] arr, int current, boolean[] visited) {
- if (arr[current] == 0) {
- return true;
- }
- visited[current] = true;
- int left = current - arr[current];
- int right = current + arr[current];
- if (left >= 0 && !visited[left]) {
- if (dfs(arr, left, visited)) {
- return true;
- }
- }
- if (right < arr.length && !visited[right]) {
- if (dfs(arr, right, visited)) {
- return true;
- }
- }
- return false;
- }
- }
- /*
- arr = [4, 2, 3, 0, 3, 1, 2], start = 5
- dfs(..., 5, [0, 0, 0, 0, 0, 0, 0])
- arr[5] -> 1
- visited[5] = true
- left = 4
- right = 6
- dfs(..., left = 4, [0, 0, 0, 0, 0, 1, 0])
- arr[4] -> 3
- visited[4] = true
- left = 1
- right = 7
- dfs(..., left = 1, [0, 0, 0, 0, 1, 1, 0])
- arr[1] -> 2
- visited[1] = true
- left = -1
- right = 3
- dfs(..., right = 3, [0, 1, 0, 0, 1, 1, 0])
- arr[3] -> 0
- return true
- return true
- return true
- return true
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement