题目
Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0.
Notice that you can not jump outside of the array at any time.
Example 1:
Input: arr = [4,2,3,0,3,1,2], start = 5Output: trueExplanation:All possible ways to reach at index 3 with value 0 are:index 5 -> index 4 -> index 1 -> index 3index 5 -> index 6 -> index 4 -> index 1 -> index 3
Example 2:
Input: arr = [4,2,3,0,3,1,2], start = 0Output: trueExplanation:One possible way to reach at index 3 with value 0 is:index 0 -> index 4 -> index 1 -> index 3
Example 3:
Input: arr = [3,0,2,1,2], start = 2Output: falseExplanation: There is no way to reach at index 1 with value 0.
Constraints:
1 <= arr.length <= 5 * 10^40 <= arr[i] < arr.length0 <= start < arr.length
题意
从数组arr的指定位置开始,每次能向左跳或向右跳arr[i]个位置,问能否到达值为0的位置。
思路
直接DFS。如果当前位置的值为0,则直接返回true;否则向两个位置递归处理,注意要先判断左右两个下一跳的位置是否合法,且对应下标是否已访问。
代码实现
Java
class Solution {public boolean canReach(int[] arr, int start) {return dfs(arr, start, new boolean[arr.length]);}private boolean dfs(int[] arr, int index, boolean[] visited) {if (arr[index] == 0) {return true;}int left = index - arr[index];int right = index + arr[index];boolean dfsLeft = false;boolean dfsRight = false;visited[index] = true;if (0 <= left && left < arr.length && !visited[left]) {dfsLeft = dfs(arr, left, visited);}if (0 <= right && right < arr.length && !visited[right]) {dfsRight = dfs(arr, right, visited);}return dfsLeft || dfsRight;}}
