题解:
方法思路:
-
贪心策略:每次在当前位置的可跳跃范围内,选择能跳得最远的位置作为下一跳的目标。
-
贪心遍历:
-
更新当前能到达的最远位置farthest
-
当遍历到当前跳跃位置最远位置cutrrent_end时,必须进行一次跳跃,并更新current_end为新的最远位置
-
若此时current_end已经超过最后一个格子,标记为可到达并终止循环
-
若此时继续前进(farthest未更新),终止循环
-
-
终止条件:当
current_end
超过或等于最后一个位置时,表示已到达终点。
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
vector<int> a(n);
for (int i = 0; i < n; i++){
cin>>a[i];
}
int jumps = 0;
int current_end = 0; //记录当前跳跃能到达的最远位置
int farthest = 0;
bool can_reach = false;
for (int i = 0; i < n; ++i) {
farthest = max(farthest, i + a[i]);
if (i == current_end) {
jumps++;
current_end = farthest;
if (current_end >= n - 1) {
can_reach = true;
break;
}
if (farthest <= i) {
// 无法继续前进
break;
}
}
}
if (can_reach) {
cout << jumps << endl;
} else {
cout << -1 << endl;
}
return 0;
}