uva 11624 Fire (BFS)

迷宫中有障碍格、火格。着火的格子每分钟向上下左右四个方向蔓延。问能否走出迷宫,求最短时间。


简单BFS,见大白书307页。


#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long uLL;
typedef long long LL;
typedef double db;
#define inf 0x3f3f3f3f
char m[1005][1005];
int T1[1005][1005],T2[1005][1005],r,c;
int mov[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
struct point
{
    int x,y;
};
void bfs1()
{
    queue<point> q;
    memset(T1,-1,sizeof(T1));
    int i,j;
    for(i=0;i<r;++i)
        for(j=0;j<c;++j)
        {
            if(m[i][j]=='F')
            {
                point tem;
                tem.x=i,tem.y=j;
                q.push(tem);
                T1[i][j]=0;
            }
        }
    while(!q.empty())
    {
        point p=q.front();
        q.pop();
        for(i=0;i<4;++i)
        {
            point tem=p;
            tem.x+=mov[i][0];
            tem.y+=mov[i][1];
            if(tem.x>=0&&tem.y>=0&&tem.x<r&&tem.y<c&&m[tem.x][tem.y]!='#'&&T1[tem.x][tem.y]==-1)
            {
                q.push(tem);
                T1[tem.x][tem.y]=T1[p.x][p.y]+1;
            }
        }
    }
}
int bfs2()
{
    queue<point> q;
    memset(T2,-1,sizeof(T2));
    int i,j;
    for(i=0;i<r;++i)
        for(j=0;j<c;++j)
        {
            if(m[i][j]=='J')
            {
                point tem;
                tem.x=i,tem.y=j;
                q.push(tem);
                T2[i][j]=0;
            }
        }
    while(!q.empty())
    {
        point p=q.front();
        q.pop();
        if(p.x==0||p.y==0||p.x==r-1||p.y==c-1) return T2[p.x][p.y]+1;
        for(i=0;i<4;++i)
        {
            point tem=p;
            tem.x+=mov[i][0];
            tem.y+=mov[i][1];

            if(T2[tem.x][tem.y]!=-1) continue;
            T2[tem.x][tem.y]=T2[p.x][p.y]+1;
            if(tem.x>=0&&tem.y>=0&&tem.x<r&&tem.y<c&&m[tem.x][tem.y]!='#'&&(T1[tem.x][tem.y]==-1||T1[tem.x][tem.y]>T2[tem.x][tem.y]))          //这里得注意火被隔断的情况。即并不是每个空格都可能着火(如果被火格障碍物隔断则某些格子T1始终为0))
                q.push(tem);
        }
    }
    return -1;
}
int main()
{
    int i,t;
    cin>>t;
    while(t--)
    {
        scanf("%d%d",&r,&c);
        queue<point> q;
        for(i=0; i<r; ++i) scanf("%s",m[i]);
        bfs1();
        int ans=bfs2();
        if(ans==-1) puts("IMPOSSIBLE");
        else printf("%d\n",ans);
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值