跳格子

跳格子

标签(空格分隔): 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值