1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public boolean canReach(int[] arr, int start) { Queue<Integer> queue = new LinkedList<>(); queue.offer(start);
while (!queue.isEmpty()) { int index = queue.poll(); if (arr[index] == 0) { return true; }
int leftIndex = index - arr[index], rightIndex = index + arr[index]; arr[index] = -1; if (leftIndex >= 0 && arr[leftIndex] >= 0) { queue.offer(leftIndex); } if (rightIndex < arr.length && arr[rightIndex] >= 0) { queue.offer(rightIndex); } }
return false; } }
|