kuangbin带你飞 简单搜索 J-fire解题报告

刷题刷题刷题,又算是遇到一个没做过的题
题目链接:https://vjudge.net/contest/221801#problem/J
emmmm读题后我首先想到bfs,然后每一次寻找子节点时用循环将火烧出来标记在地图上,写完后提交,情理之中出现了tle。在网上搜了一下参考了大神的思路,发现应该两次宽搜,一次搜火的时间,一次搜Joe的时间,注意是先搜火,若joe到边缘的时间小于火到边缘的时间,则输出,找完没有则输出impossible。
talk is cheap

#include<bits/stdc++.h>
using namespace std;
const int d[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
struct node{
    int x,y,step;
    node(){}
    node(int q,int w,int e):x(q),y(w),step(e){}
};
char mat[1110][1110];
bool vis[1110][1110];
int ste[1100][1100];
int n,m,t,sx,sy;
queue<node> q1,q2;//由于需要再主程序里push,所有定义为全局,
                 ///但是要记得在每个测试数据那儿pop(),不然会wa(微笑
void bfs();
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie();
    cin>>t;
    while(t--){
        while(!q1.empty())
            q1.pop();
        while(!q2.empty())
            q2.pop();//清空队列,避免上一个测试数据污染当前
        memset(mat,0,sizeof(mat));
        memset(vis,0,sizeof(vis));
        memset(ste,0x3f,sizeof(ste));
        cin>>n>>m;
        for (int i=0;i<n;i++){
            cin>>mat[i];
            for (int j=0;j<m;j++)
                if (mat[i][j]=='J'){
                    q1.push(node(i,j,0));
                    sx=i;
                    sy=j;
                    //vis[i][j]=1;
                }
                else if (mat[i][j]=='F'){
                    q2.push(node(i,j,0));
                    vis[i][j]=1;//先搜火
                }

        }
        bfs();
    }
    return 0;
}
void bfs(){
    while(!q2.empty()){
        node now=q2.front();
        q2.pop();
        if (now.x==0||now.y==0||now.x==n-1||now.y==m-1)
            ste[now.x][now.y]=min(ste[now.x][now.y],now.step);
        for (int i=0;i<4;i++){
            int tx=now.x+d[i][0];
            int ty=now.y+d[i][1];
            if (tx>-1&&ty>-1&&tx<n&&ty<m&&mat[tx][ty]!='#'&&!vis[tx][ty]){
                q2.push(node(tx,ty,now.step+1));
                vis[tx][ty]=1;
            }
        }
    }
    memset(vis,0,sizeof(vis));
    vis[sx][sy]=1;
    while(!q1.empty()){
        node now=q1.front();
        q1.pop();
        if (now.x==0||now.x==n-1||now.y==0||now.y==m-1)
        if(now.step<ste[now.x][now.y]){
            cout<<now.step+1<<"\n";
            return;
        }
        for (int i=0;i<4;i++){
            int tx=now.x+d[i][0];
            int ty=now.y+d[i][1];
            if (tx>-1&&ty>-1&&ty<m&&tx<n&&!vis[tx][ty]&&mat[tx][ty]!='#'){
                vis[tx][ty]=1;
                q1.push(node(tx,ty,now.step+1));
            }
        }
    }
    cout<<"IMPOSSIBLE\n";
}

好了,感谢浏览,幸福开心呢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值