UVA 11624 Fire!

来源:互联网 发布:巨人网络上市 编辑:程序博客网 时间:2024/05/19 01:10

题目内容

就是一个人在一个迷宫中,但是迷宫中有一些火种同时会向附近蔓延,问此人能不能不经过着火区域逃出迷宫,需要注意的是,着火点可能有多个,但是迷宫中只有一个人。

题目分析

首先利用建立一个time数组,保存火烧到该点所需要的时间,同时也要初始化time[]数组为一个无限大的数,即如果火烧不到该地点,那么该地点可以在任何时刻都可以被人走,首先写第一个bfs1求出火烧到能烧到的点所需要的最少时间,同时要用一个结构体数组保存所有着火点,然后往queue添加所有的着火点,并将着火时间初始化为0.
然后再用一个bfs2求出人能逃出迷宫所需要的最小时间,注意如果人到达该点的时间小于该点起火的时间,这个状态才能被加入队列。

#include <cstdio>#include <cstring>#include <iostream>#include <queue>#include <algorithm>using namespace std;const int maxn = 1005;const int INF = 0x3f3f3f3f;bool vis[maxn][maxn];char maze[maxn][maxn];int tim[maxn][maxn];int n,m,flag;int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};struct Node{    int x,y,t;    Node(){}    Node(int a,int b,int c):x(a),y(b),t(c){}}node[maxn*maxn];void init(){    for(int i = 0; i < maxn; i++)        for(int j = 0; j < maxn; j++)            tim[i][j] = INF;}void bfs1(){    queue <Node> que;    Node pre;    while(!que.empty()) que.pop();    for(int i = 0; i < flag; i++)        que.push(node[i]);    while(!que.empty())    {        pre = que.front();        que.pop();        for(int i = 0; i < 4; i++)        {            int xx = pre.x + dir[i][0];            int yy = pre.y + dir[i][1];            if(xx < 0 || xx >= n || yy < 0 || yy >= m)                continue;            if(maze[xx][yy] != '#' && !vis[xx][yy])            {                vis[xx][yy] = true;                tim[xx][yy] = pre.t+1;                que.push(Node(xx,yy,pre.t+1));            }        }    }}int bfs2(int sx,int sy){    queue <Node> que;    Node pre;    memset(vis,false,sizeof(vis));    que.push(Node(sx,sy,0));    vis[sx][sy] = true;    while(!que.empty())    {        pre = que.front();        que.pop();        for(int i = 0; i < 4; i++)        {            int xx = pre.x + dir[i][0];            int yy = pre.y + dir[i][1];            if(xx < 0 || xx >= n || yy < 0|| yy >= m)                return pre.t+1;            if(maze[xx][yy] != '#' && !vis[xx][yy] && tim[xx][yy] > pre.t+1)            {                vis[xx][yy] = true;                que.push(Node(xx,yy,pre.t+1));            }        }    }    return 0;}int main(){    int T,sx,sy;    scanf("%d", &T);    while(T--)    {        init();        memset(vis,false,sizeof(vis));        scanf("%d %d", &n, &m);        for(int i = 0; i < n; i++)            scanf("%s", maze[i]);        flag = 0;        for(int i = 0; i < n; i++)            for(int j = 0; j < m; j++)                if(maze[i][j] == 'F')                {                    node[flag].x = i;                    node[flag].y = j;                    node[flag++].t = 0;                    vis[i][j] = true;                    tim[i][j] = 0;                }                else if(maze[i][j] == 'J')                {                    sx = i;                    sy = j;                }        bfs1();        int ans = bfs2(sx,sy);        if(!ans)            printf("IMPOSSIBLE\n");        else            printf("%d\n", ans);    }    return 0;}
1 0
原创粉丝点击