百练 4116 拯救行动

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn=200+5;
char p[maxn][maxn];
int n,m,xm,ym,xw,yw;
int vis[maxn][maxn];
struct node{
    int l,x,y;
    int steps;
    node(int l,int x,int y,int steps) : l(l),x(x),y(y),steps(steps) {};
};
void BFS()
{
    vis[xm][ym]=1;
    queue<node> q;
    while(!q.empty()) q.pop();
    q.push(node(1,xm,ym,0));
    while(!q.empty())
    {
        node ans=q.front();
        q.pop();
        int x=ans.x,y=ans.y,steps=ans.steps;
        if(ans.x==xw&&ans.y==yw) {printf("%d\n",steps);return ;}
        if(ans.l==0){
            q.push(node(1,x,y,steps+1));
        }
        else{
            if(x>1&&!vis[x-1][y]){
                vis[x-1][y]=1;
                if(p[x-1][y]=='@'||p[x-1][y]=='a') q.push(node(1,x-1,y,steps+1));
                else if(p[x-1][y]=='x') q.push(node(0,x-1,y,steps+1));
            }
            if(y>1&&!vis[x][y-1]){
                vis[x][y-1]=1;
                if(p[x][y-1]=='@'||p[x][y-1]=='a') q.push(node(1,x,y-1,steps+1));
                else if(p[x][y-1]=='x') q.push(node(0,x,y-1,steps+1));
            }
            if(x<n&&!vis[x+1][y]){
                vis[x+1][y]=1;
                if(p[x+1][y]=='@'||p[x+1][y]=='a') q.push(node(1,x+1,y,steps+1));
                else if(p[x+1][y]=='x') q.push(node(0,x+1,y,steps+1));
            }
            if(y<m&&!vis[x][y+1]){
                vis[x][y+1]=1;
                if(p[x][y+1]=='@'||p[x][y+1]=='a') q.push(node(1,x,y+1,steps+1));
                else if(p[x][y+1]=='x') q.push(node(0,x,y+1,steps+1));
            }
        }
    }
    printf("Impossible\n");
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        memset(vis,0,sizeof(vis));
        memset(p,0,sizeof(p));
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                cin>>p[i][j];
                if(p[i][j]=='r') xm=i,ym=j;
                if(p[i][j]=='a') xw=i,yw=j;
            }
        }
        BFS();
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值