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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun canReach(arr: IntArray, start: Int): Boolean { | |
val queue = mutableListOf<Int>() | |
queue.add(start) | |
var nextIndex = 0 | |
val set = mutableSetOf<Int>() | |
while(queue.isNotEmpty()) { | |
val index = queue.first() | |
queue.removeAt(0) | |
if(arr[index] == 0) { | |
return true | |
} | |
nextIndex = index + arr[index] | |
if(nextIndex < arr.size && !set.contains(nextIndex)) { | |
queue.add(nextIndex) | |
set.add(nextIndex) | |
} | |
nextIndex = index - arr[index] | |
if(nextIndex > -1 && !set.contains(nextIndex)) { | |
queue.add(nextIndex) | |
set.add(nextIndex) | |
} | |
} | |
return false | |
} | |
} | |
沒有留言:
張貼留言