You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
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
这道题是 Jump Game 系列的第三道,前面两道分别是 Jump Game 和 Jump Game II,与之前不同的是,这道题给了一个起始位置 start,而且说了对于某个位置i,可以跳到 i + arr[i] 或者 i - arr[i] 这两个位置,问是否可以到达数字为0的位置,注意这里不是下标为0的位置,而是该位置上的数字为0。博主最先想到的方法是用 BFS 来做,因为每个位置相当于可以展开到两个新的位置,新的位置再展开,这样所有能到的位置都展开了,就可以知道有没有数字0了。
class Solution {
public:
bool canReach(vector<int>& arr, int start) {
int n = arr.size();
vector<bool> visited(n);
queue<int> q{{start}};
visited[start] = true;
while (!q.empty()) {
auto t = q.front(); q.pop();
if (arr[t] == 0) return true;
int left = t - arr[t], right = t + arr[t];
if (left >= 0 && !visited[left]) {
visited[left] = true;
q.push(left);
}
if (right < n && !visited[right]) {
visited[right] = true;
q.push(right);
}
}
return false;
}
};
Activity
[-][LeetCode] 1306. Missing Problem[/-][+][LeetCode] 1306. Jump Game III[/+]