UVa11624(逃离火焰问题)

复制代码
#include"cstdio"
#include"queue"
#include"cstring"
using namespace std;
const int MAXN=1005;
const int INF=0X7fffffff;
typedef pair<int,int> P;
char mp[MAXN][MAXN];
int ft[MAXN][MAXN];
int jt[MAXN][MAXN];
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int n,m;
int sy,sx;
void bfs1()//第一次广搜确定 fire到达passable square的时间 
{
    queue<P> que;
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
        {
            ft[i][j]=INF;
            if(mp[i][j]=='F')
            {
                que.push(P(i,j));
                ft[i][j]=0;
            }    
        }
    while(!que.empty())
    {
        P now = que.front();que.pop();
        for(int i=0;i<4;i++)
        {
            int ny=now.first+dy[i];
            int nx=now.second+dx[i];
            if(0<=ny&&ny<n&&0<=nx&&nx<m&&mp[ny][nx]!='#')
            {
                int dist=ft[now.first][now.second]+1;
                if(dist<ft[ny][nx])
                {
                    ft[ny][nx]=dist;
                    que.push(P(ny,nx));
                }
            }
        }
    }
}
void bfs2()
{
    memset(jt,-1,sizeof(jt));
    queue<P> que;
    que.push(P(sy,sx));
    jt[sy][sx]=0;
    while(!que.empty())
    {
        P now=que.front();que.pop();
        if(now.first==0||now.first==n-1||now.second==0||now.second==m-1)
        {
            printf("%d\n",jt[now.first][now.second]+1);//逃出迷宫,注意+1 
            return ;
        }
        for(int i=0;i<4;i++)
        {
            int ny=now.first+dy[i];
            int nx=now.second+dx[i];
            if(0<=ny&&ny<n&&0<=nx&&nx<m&&mp[ny][nx]!='#'&&jt[ny][nx]==-1)
            {
                int dist=jt[now.first][now.second]+1;
                if(dist<ft[ny][nx])//若在该时刻该点没有火焰到达说明可行 
                {
                    jt[ny][nx]=dist;
                    que.push(P(ny,nx));
                }        
            }
        }
    }
    
    printf("IMPOSSIBLE\n");
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        scanf("%*c");
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                scanf("%c",&mp[i][j]);
                if(mp[i][j]=='J')
                {
                    sy=i,sx=j;
                }        
            }
            scanf("%*c");
        }
        bfs1();
        bfs2();
    }
    
    return 0;
}
复制代码

 

posted on   vCoders  阅读(213)  评论(0编辑  收藏  举报

努力加载评论中...

导航

点击右上角即可分享
微信分享提示