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 = 5
Output: true
Explanation:
All possible ways to reach at index 3 with value 0 are:
index 5 -> index 4 -> index 1 -> index 3
index 5 -> index 6 -> index 4 -> index 1 -> index 3
给一个数组,从start的index出发,每次能左移或右移arr[start]个位置
问能不能走到值为0的index处
显然要用DFS或者BFS
用DFS要注意
- 要有visited数组,访问过的地方不要再重复访问,否则容易出现死循环
- 如果不修改原数组数值的情况下,需要另有一个数组记录访问过的位置是否能到达0,要么就改变原数组数值,记录visited。这样就避免了重复计算
- 注意index是否超出了数组边界,判断index是否<0或者>=arr.length
这里不改变原数组的值
public boolean canReach(int[] arr, int start) {
if(arr == null || start < 0 || start >= arr.length) {
return false;
}
boolean[] bVisited = new boolean[arr.length];
boolean[] bReach = new boolean[arr.length];
return dfs(arr, start, bVisited, bReach);
}
boolean dfs(int[] arr, int start, boolean[] bVisited, boolean[] bReach) {
if(start < 0 || start >= arr.length) return false;
if(bVisited[start]) return bReach[start];
bVisited[start] = true;
if(arr[start] == 0) {
bReach[start] = true;
return true;
}
if(bReach[start]) return true;
return dfs(arr, start - arr[start], bVisited, bReach) || dfs(arr, start + arr[start], bVisited, bReach);
}