Given an array of non-negative integers
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
Example 2:
Input: arr = [4,2,3,0,3,1,2], start = 0 Output: true Explanation: 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 = 2 Output: false Explanation: There is no way to reach at index 1 with value 0.
Constraints:
1 <= arr.length <= 5 * 104 0 <= arr[i] < arr.length 0 <= start < arr.length
Solution
這題可以用 BFS 的想法思考
滿像就是在迷宮裡面,能不能從入口走到出口,只要找到一個答案就結束
所以用個 queue 儲存合法可以走的 index,同時也用個 set 來記錄走過的路
如果都沒找到,就回傳 false 即可
kotlin
沒有留言:
張貼留言