跳格子
标签(空格分隔): bfs
Description
Wx最近在玩一个跳格子的游戏,游戏的规则如下:给出n个格子,每个格子有一个数字x,代表在该位置可以向右跳0-x步,现在Wx需要算出最少的跳跃次数,从最左边的格子跳到最右边的格子,输出跳跃的次数,若跳不到,则输出-1.
Intput
输入一个t,表示有t组测试数据
对于每组测试数据读入一个n表示格子的个数(2 <=n<=20), 下面一行n个数,表示每个格子上的数字是多少
Output
输出每次的最小跳跃次数,若跳不到,则输出-1
Sample Input
4
5
1 2 3 4 5
5
4 3 2 1 0
6
1 1 1 1 1 1
7
4 1 1 1 0 2 4
Sample Output
3
1
5
-1
思路
这个题可以用bfs,跟迷宫问题一样,将可能的点都压入队列,下面看bfs代码实现
代码
#include <iostream>
#include <queue>
using namespace std;
int lattice[100]; //格子数组
struct node {
int x; //记录格子位置
int steps; //记录步数
node(int i, int j):x(i), steps(j) {}
};
int getTheBest(int end) {
node now(0, 0);
queue<node> q;
q.push(now);
while (!q.empty()) {
now = q.front();
q.pop();
for (int i = 1; i <= lattice[now.x]; i++) {
int y = now.x + i; //即每一步都压入
node newOne(y, now.steps + 1);
if (newOne.x == end) return newOne.steps;
q.push(newOne);
}
}
return -1; //队列已空找不到最小值,返回-1
}
int main() {
int times, nums, k;
cin >> times;
while (times--) {
cin >> nums;
for (int i = 0; i < nums; i++)
cin >> lattice[i];
int result = getTheBest(nums - 1);
cout << result << endl;
}
return 0;
}