汤圆の拯救计划

14 篇文章 0 订阅
QAQ蒟蒻每一次都可以移动到相邻的非墙的格子中,每次移动都要花费1个单位的时间

有公共边的格子定义为相邻
Input

一开始为一个整数T代表一共有T组数据

每组测试数据的第一行有两个整数n,m (2<=n,m<=300)

接下来的n行m列为大魔王的迷宫,其中

’#’为墙壁,‘_‘为地面

A代表QAQ蒟蒻,O代表汤圆公主:

Output

一组数据输出一个整数代表从QAQ蒟蒻到汤圆的位置的最短时间

如果QAQ蒟蒻不能到达汤圆的位置,输出-1

Example Input
2
3 3
__A
_##
__O
2 2
A#
#O
Example Output

6
-1

很典型的搜索题,结果比赛的时候我居然写了DFS(汗...  所以一直超时,用BFS,得到的一定是最短的

#include <iostream>
#include <cstdio>
#include <queue>

using namespace std;
const int N = 310;

typedef struct node
{
    int u, v, step;     //u,v为坐标,step为步数
}Node;
char str[N][N];
bool map[N][N];
int n, m;
int xx[4] = {1,0,0,-1}, yy[4] = {0,1,-1,0};

int BFS(int s, int e)
{
    map[s][e] = 1;
    Node t, x;
    queue<Node> q;
    t.u = s;
    t.v = e;
    t.step = 0;
    q.push(t);
    while(!q.empty())
    {
        t = q.front();
        q.pop();
        if(str[t.u][t.v] == 'O')
            return t.step;
        for(int i = 0; i < 4; i++)  //四个方向搜索
        {
            x.u = t.u + xx[i];
            x.v = t.v + yy[i];
            if(x.u >= 0 && x.u < n && x.v >= 0 && x.v < m && str[x.u][x.v] != '#' && !map[x.u][x.v])
            {
                x.step = t.step + 1;
                q.push(x);
                map[x.u][x.v] = 1;

            }
        }
    }
    return 0;
}
int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d%d", &n, &m);
        memset(map, 0, sizeof(map));
        int i, j;
        int x, y;
        for(i = 0; i < n; i++)
            scanf("%s", str[i]);
        for(i = 0; i < n; i++)
            for(j = 0; j < m; j++)
                if(str[i][j] == 'A')  //得到起点A
                {
                    x = i;
                    y = j;
                    break;
                }
        int re = BFS(x, y);
        if(re == 0)
            printf("-1\n");
        else
            printf("%d\n", re);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值