leetcode 1306. Jump Game III

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 anyindex 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 * 10^4
  • 0 <= arr[i] < arr.length
  • 0 <= start < arr.length

题目大意:给定一个数组arr和数组的索引start,当在索引i位置,可以跳到 $i + arr[i]$或者$i - arr[i]$处。注:不能跳到数组外。

思路:可能的路径可以限制为每个位置只跳过一次,这样可以减小路径长度。当在某一个位置,向左和向右跳的位置都已经跳过时,表明这个位置不可能到达0.

用bfs很容易解决。

 1 class Solution {
 2 public:
 3     bool canReach(vector<int>& arr, int start) {
 4         // ios_base::sync_with_stdio(false);
 5         // cin.tie(nullptr);
 6         // cout.tie(nullptr);
 7         bool flag = false; //判定是否可到达的标志
 8         int len = arr.size(); 
 9         vector<bool> visited(len, false); //广搜过程中每个元素只能访问一次
10         queue<int> q;
11         
12         if (arr[start] == 0)
13             return true;
14         q.push(start);
15         visited[start] = true;
16         while (!q.empty()) {
17             int sz = q.size(); //当前层次的队列中的所有元素进行一次跳跃
18             for (int i = 0; i < sz; i++) {
19                 int index = q.front();
20                 q.pop();
21                 int left = index + arr[index], right = index - arr[index];
22                 //向左跳,如果计算得到的索引还在数组内,并且之前没有跳过,就可以跳
23                 if (left >= 0 && left < len && (visited[left] == false)) {
24                     if (arr[left] == 0) { //如果此时数组值为0,则返回true
25                         flag = true;
26                         return flag;
27                     } else {
28                         visited[left] = true;
29                         q.push(left);
30                     }
31                 } 
32                 //向右跳,如果计算得到的索引还在数组内,并且之前没有跳过,就可以跳
33                 if (right >= 0 && right < len && (visited[right] == false)) {
34                     if (arr[right] == 0) { //如果此时数组值为0,则返回true
35                         flag = true;
36                         return flag;
37                     } else {
38                         visited[right] = true;
39                         q.push(right);
40                     }
41                 }
42             }
43         }
44         return false;
45     }
46 };

猜你喜欢

转载自www.cnblogs.com/qinduanyinghua/p/12119848.html
今日推荐