Fire! UVA - 11624

Posted sanshi-2018

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Fire! UVA - 11624相关的知识,希望对你有一定的参考价值。

#include<bits/stdc++.h>
using namespace std;

struct Node{
    int r, c, dis;
    Node(int r, int c):r(r), c(c){}
};

const int maxn = 1000 + 3;
int R, C;
char maze[maxn][maxn];
int fire[maxn][maxn];
int vis[maxn][maxn];

const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};

void solve()
{
    int r0, c0;
    queue<Node>q;
    memset(fire, -1, sizeof(fire));
    for(int i = 0; i < R; i++){
        for(int j = 0; j < C; j++){
            char ch = maze[i][j];
            if(ch == . || ch == #) continue;
            if(ch == F){
                q.push(Node(i, j));
                fire[i][j] = 0;
            }else{
                r0 = i, c0 = j;
            }
        }
    }


    while(!q.empty()){
        Node u = q.front(); q.pop();
        int r = u.r, c = u.c;
        for(int i = 0; i < 4; i++){
            int rr = r + dx[i];
            int cc = c + dy[i];
            if(rr >= 0 && rr < R && cc >= 0 && cc < C && maze[rr][cc] != # && fire[rr][cc] == -1){
                Node v(rr, cc);
                q.push(v);
                fire[rr][cc] = fire[r][c] + 1;
            }
        }
    }
//    for(int i = 0; i < R; i++){
//        for(int j = 0; j < C; j++){
//            printf("%d ", fire[i][j]);
//        }
//        printf("
");
//    }

    memset(vis, -1, sizeof(vis));
    vis[r0][c0] = 0;
    q.push(Node(r0, c0));
    while(!q.empty()){
        Node u = q.front(); q.pop();
        int r = u.r, c = u.c;
        for(int i = 0; i < 4; i++){
            int rr = r + dx[i];
            int cc = c + dy[i];
            if(rr < 0 || rr == R || cc < 0 || cc == C){
                cout << vis[r][c] + 1 << endl;
                return;
            }
            if(maze[rr][cc] == . && vis[rr][cc] == -1 && (fire[rr][cc] == - 1 || vis[r][c] + 1 < fire[rr][cc])){  //fire[rr][cc] == -1 should‘t be ignored.
                Node v(rr, cc);
                q.push(v);
                vis[rr][cc] = vis[r][c] + 1;
            }
        }
    }
    cout << "IMPOSSIBLE" << endl;
    return;
}

int main()
{
//    freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
    int T;
    cin >> T;
    int cnt = 0;
    while(T--){
        cin >> R >> C;
        for(int i = 0; i < R; i++){
            scanf("%s", maze[i]);
        }
        solve();
    }
    return 0;
}

 

以上是关于Fire! UVA - 11624的主要内容,如果未能解决你的问题,请参考以下文章

Fire! UVA - 11624

UVA 11624 Fire

[UVa11624]Fire!(BFS)

UVa 11624 Fire!(着火了!)

BFS Fire! UVA - 11624

UVA11624(KB1-J)