UVA 11624 Fire! (BFS)

45 篇文章 0 订阅
44 篇文章 0 订阅

该题是一道比较简单的BFS, 难点在于火会蔓延,那么我们不妨分开进行两次BFS,一次标记好每一处第一次被火烧到的时间,第二次就可以用这个时间标记来进行BFS了。

之前也有过一次记录下时间标记来利用的情况 ,算是个技巧吧。

细节参见代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
#include<list>
#include<set>
#include<cmath>
using namespace std;
typedef long long ll;
const int mod = 1e9 + 7;
const int INF = 1e9;
const int maxn = 1000 + 15;
int n,m,T,a,b,c,t,d[maxn][maxn],vis[maxn][maxn];
int dx[] = {0,1,0,-1};
int dy[] = {1,0,-1,0};
struct node{
    int r,c;
    node(int r=0,int c=0):r(r),c(c) {}
    bool operator == (const node& rhs) const {
        return r == rhs.r && c == rhs.c;
    }
}start;
vector<node> g;
char s[maxn][maxn];
void bfs1() {
    queue<node> q;
    memset(vis,-1,sizeof(vis));
    for(int i=0;i<g.size();i++) {
        node u = g[i];
        vis[u.r][u.c] = 0;
        q.push(u);
    }
    while(!q.empty()) {
        node u = q.front(); q.pop();
        for(int i=0;i<4;i++) {
            int x = u.r + dx[i], y = u.c + dy[i];
            if(x < 0 || x >= n || y < 0 || y >= m) continue;
            if(vis[x][y] == -1 && s[x][y] != '#') {
                vis[x][y] = vis[u.r][u.c] + 1;
                q.push(node(x,y));
            }
        }
    }
}
int bfs(node start) {
    queue<node> q;
    memset(d,-1,sizeof(d));
    d[start.r][start.c] = 0;
    q.push(start);
    while(!q.empty()) {
        node u = q.front(); q.pop();
        if(u.r == 0 || u.r == n-1 || u.c == 0 || u.c == m-1) return d[u.r][u.c] + 1;
        for(int i=0;i<4;i++) {
            int x = u.r + dx[i], y = u.c + dy[i];
            if(x < 0 || x >= n || y < 0 || y >= m) continue;
            if(d[x][y] == -1 && s[x][y] != '#' && (vis[x][y] > d[u.r][u.c]+1 || vis[x][y] < 0)) {
                d[x][y] = d[u.r][u.c] + 1;
                q.push(node(x,y));
            }
        }
    }
    return -1;
}
int main() {
    scanf("%d",&T);
    while(T--) {
        scanf("%d%d",&n,&m);
        g.clear();
        for(int i=0;i<n;i++) scanf("%s",s[i]);
        for(int i=0;i<n;i++) {
            for(int j=0;j<m;j++) {
                if(s[i][j] == 'J') start = node(i,j);
                if(s[i][j] == 'F') g.push_back(node(i,j));
            }
        }
        bfs1();
        int ans = bfs(start);
        if(ans < 0) 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、付费专栏及课程。

余额充值