#1306. 跳跃游戏 III
难度:中等
类似题目:55.跳跃游戏
题目描述
解题思路
1、BFS
很经典的BFS啦
public static boolean canReach(int[] arr, int start) {
if(arr[start] == 0)
return true;
int n = arr.length;
Queue<Integer> queue = new LinkedList<Integer>();
int[] visit = new int[n];
queue.add(start);
visit[start] = 1;
while(!queue.isEmpty()) {
int s = queue.poll();
if(arr[s] == 0)
return true;
int left = s-arr[s];
int right = s+arr[s];
if(right < n && visit[right] != 1) {
queue.add(right) ;
visit[right] = 1;
}
if(left >= 0 && visit[left] != 1) {
queue.add(left) ;
visit[left] = 1;
}
}
return false;
}
内存居然超越100%,明明感觉队列什么占了挺多内存的,就很不懂
2、DFS
public boolean canReach(int[] arr, int start) {
if(arr[start] == 0)
return true;
int n = arr.length;
int[] visit = new int[n];
return dfsJump(arr,visit,start);
}
public boolean dfsJump(int[] arr,int[] visit,int s) {
int n = arr.length;
if(s < 0 || s >= n || visit[s] == 1)
return false;
int left = s-arr[s];
int right = s+arr[s];
if(arr[s] == 0)
return true;
visit[s] = 1;
return dfsJump(arr, visit, left) || dfsJump(arr, visit, right);
}