uva11624搜索

搜索,两次BFS,第一遍BFS处理出火烧的时间,第二次BFS逃跑路线,注意不只有一处火。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=1005;
const int inf=0x3f3f3f3f;
struct point
{
    int x,y;
};
int fire[maxn][maxn],n,m;
char gra[maxn][maxn];
int pos[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
bool check(int x,int y)
{
    if(x>=1&&x<=n&&y<=m&&y>=1) return 1;
    else return 0;
}
void bfs1(int x,int y)
{
    fire[x][y]=1;
    point u;
    u.x=x,u.y=y;
    queue<point>q;
    q.push(u);
    while(!q.empty())
    {
        u=q.front();
        q.pop();
        for(int i=0;i<4;i++)
        {
            point v;
            v.x=u.x+pos[i][0],v.y=u.y+pos[i][1];
            if(fire[u.x][u.y]+1<fire[v.x][v.y]&&check(v.x,v.y)&&gra[v.x][v.y]!='#')
            {
                q.push(v);
                fire[v.x][v.y]=fire[u.x][u.y]+1;
            }
        }
    }
}
int path[maxn][maxn];
int bfs2(int x,int y)
{
    path[x][y]=1;
    point u;
    u.x=x,u.y=y;
    queue<point>q;
    q.push(u);
    while(!q.empty())
    {
        u=q.front();
        q.pop();
        for(int i=0;i<4;i++)
        {
            point v;
            v.x=u.x+pos[i][0],v.y=u.y+pos[i][1];
            if(!check(v.x,v.y)) return path[u.x][u.y];
            if(!path[v.x][v.y]&&gra[v.x][v.y]!='#'&&check(v.x,v.y))
            {
                path[v.x][v.y]=path[u.x][u.y]+1;
                if(path[v.x][v.y]<fire[v.x][v.y])
                {
                    q.push(v);
                }
            }
        }
    }
    return -1;
}
int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    int t;
    point s,e;
    scanf("%d",&t);
    while(t--)
    {
        cin>>n>>m;
        for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++) fire[i][j]=inf;
        queue<point>q;
        memset(gra,0,sizeof(gra));
        memset(path,0,sizeof(path));
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                cin>>gra[i][j];
                if(gra[i][j]=='F')
                {
                    s.x=i,s.y=j;
                    q.push(s);
                }
                if(gra[i][j]=='J') e.x=i,e.y=j;
            }
        }
        while(!q.empty())
        {
            s=q.front();
            q.pop();
            bfs1(s.x,s.y);
        }
        int ans=bfs2(e.x,e.y);
        if(ans==-1) printf("IMPOSSIBLE\n");
        else printf("%d\n",ans);

    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值