uva Fire!

14 篇文章 0 订阅

/*有可能存在墙壁将大火全都围住,火蔓延不到的区域*/
#include <stdio.h>
#include <cstring>
#include <queue>
#include <iostream>
using namespace std;
const int maxn=1005;
char map[maxn][maxn];
bool vis[maxn][maxn];
int step[maxn][maxn];
struct point
{
    int x,y,t;
};
int dx[]= {0,0,1,-1};
int dy[]= {1,-1,0,0};
int n,m;
void bfs1()
{
    queue <point> q;
    point t,tt;
    for(int i=0; i<n; i++)
        for(int j=0; j<m; j++)
            if(map[i][j]=='F')
                t.x=i,t.y=j,t.t=0,q.push(t),vis[i][j]=true;
    while(!q.empty())
    {
        t=q.front();
        q.pop();
        for(int i=0;i<4;i++)
        {
            int x=t.x+dx[i];
            int y=t.y+dy[i];
            if(!vis[x][y]&&x>=0&&x<n&&y>=0&&y<m&&map[x][y]!='#')
            {
                vis[x][y]=true;
                tt.x=x,tt.y=y,tt.t=t.t+1;
                step[x][y]=tt.t;
                q.push(tt);
            }
        }
    }
}
int bfs2(point s)
{
    queue <point> q;
    q.push(s);
    point pre,now;
    memset(vis,false,sizeof(vis));
    vis[s.x][s.y]=true;
    while(!q.empty())
    {
        pre=q.front();
        q.pop();
        if(pre.x==0||pre.y==0||pre.x==n-1||pre.y==m-1)
            return pre.t+1;
        for(int i=0;i<4;i++)
        {
            int x=dx[i]+pre.x;
            int y=dy[i]+pre.y;
            if(x>=0&&x<n&&y>=0&&y<m&&!vis[x][y]&&map[x][y]!='#'&&(step[x][y]==-1||step[x][y]>pre.t+1))
            {//有可能存在墙壁将大火全都围住,火蔓延不到的区域
                vis[x][y]=true;
                now.t=pre.t+1;
                now.x=x,now.y=y;
                q.push(now);
            }
        }
    }
    return -1;
}
int main()
{
    //freopen("in.txt","r",stdin);
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        memset(vis,false,sizeof(vis));
        memset(step,-1,sizeof(step));
        point s;
        for(int i=0; i<n; i++)
        {
            scanf(" %s",map[i]);
            for(int j=0; j<m; j++)
                if(map[i][j]=='J')
                    s.x=i,s.y=j,s.t=0;
        }
        bfs1();
       /* for(int i=0;i<n;i++)
        {for(int j=0;j<m;j++)
        printf("%d ",step[i][j]);
        printf("\n");}*/
        int ans=bfs2(s);
        if(ans==-1) printf("IMPOSSIBLE\n");
        else printf("%d\n",ans);
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值