sdut-3474 汤圆の拯救计划

Problem Description

又到了汤圆星球一年一度的汤圆节了,但是大魔王却过来把汤圆公主抓走了Σ( ° △ °|||)︴

身为汤圆骑士的QAQ蒟蒻自然而然的肩负着拯救汤圆的使命

QAQ蒟蒻经历了千辛万苦(并没有)之后,来到了大魔王的城堡,根据情报,汤圆公主就被大魔王放在城堡内,然后QAQ蒟蒻发现自己是一个路

痴,所幸的是他拿到了大魔王的城堡的地图,而且在这上面标注了自己和汤圆公主的位置,那么问题来了,聪明的你能帮他计算出需要多少单位

的时间来赶到汤圆公主的位置吗?

Ps:QAQ蒟蒻每一次都可以移动到相邻的非墙的格子中,每次移动都要花费1个单位的时间

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

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

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

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

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

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

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

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

Sample Input
2
3 3
__A
_##
__O
2 2
A#

O

Sample Output
6
-1
Hint
Source
QAsQ

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

using namespace std;
int n,m;
char mm[303][303];
bool vis[303][303];
int step[4][2]={
    {0,1},{0,-1},
    {1,0},{-1,0}
};
struct node
{
    int x,y,ans;
}t;

void bfs(int x, int y)
{
    queue<node>q;
    t.x = x;
    t.y = y;
    t.ans = 0;
    q.push(t);
    vis[t.x][t.y] = true;
    while(!q.empty())
    {
        node cur = q.front();
        q.pop();
        if(mm[cur.x][cur.y] == 'O')
        {
            cout<<cur.ans<<endl;
            return ;
        }
        //cout<<cur.x<<' '<<cur.y<<' '<<cur.ans<<endl;

        for (int i = 0; i < 4; ++i)
        {
            t.x = cur.x + step[i][0];
            t.y = cur.y + step[i][1];

            if(t.x < 1||t.x > n ||t.y < 1|| t.y >m)
                continue;
            //cout<<"t.x t.y "<<t.x<<' '<<t.y<<endl;
            if(!vis[t.x][t.y] && mm[t.x][t.y] != '#')
            {
                // cout<<t.x<<' '<<t.y<<endl;

                t.ans = cur.ans+1;
                vis[t.x][t.y] = true;
                q.push(t);
            }
        }
    }
    cout<<-1<<endl;
}
int main(int argc, char const *argv[])
{
    int T;
    cin>>T;
    while(T--)
    {
        memset(vis,false,sizeof(vis));
        int x,y;
        cin>>n>>m;
        for (int i = 1; i <= n; ++i)
        {
            for (int j = 1; j <= m; ++j)
            {
                char c;
                cin>>c;
                mm[i][j] = c;
                if(c == 'A')
                {
                    x = i;
                    y = j;
                }
            }
        }
        //cout<<x<<y<<endl;
        bfs(x,y);
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值