设为首页 加入收藏

TOP

UVA11624-Fire!(两次bfs)
2015-07-20 17:36:54 来源: 作者: 【 】 浏览:3
Tags:UVA11624-Fire 两次 bfs

题目链接


题意:你的任务是帮助J走出一个大火蔓延的迷宫。J每分钟可以超上下左右四个方向移动,而所有着火的格子都会往四周蔓延。迷宫中有一些障碍,J和火都无法进入。当J走到一个迷宫的边界格子时,我们认为他已经走出了迷宫。

思路:这是大白上面的一道题目,其实只要将每个格子什么时间着火处理出来就可以了。两次BFS,第一次处理格子着火的时间,第二次BFS就是判断是否能在最短时间内走出去。

代码:

#include 
  
   
#include 
   
     #include 
    
      #include 
     
       #include 
      
        using namespace std; const int MAXN = 1005; const int INF = 0x3f3f3f3f; const int dx[] = {-1, 0, 0, 1}; const int dy[] = {0, -1, 1, 0}; struct node{ node (int xx, int yy, int dd) { x = xx; y = yy; d = dd; } int x, y, d; }; char g[MAXN][MAXN]; int vf[MAXN][MAXN], vm[MAXN][MAXN], T[MAXN][MAXN]; int r, c, sx, sy; queue
       
         qf; void bfs_fire() { while (!qf.empty()) { node u = qf.front(); qf.pop(); node v = u; for (int i = 0; i < 4; i++) { int tx = u.x + dx[i]; int ty = u.y + dy[i]; if (tx < 0 || tx >= r || ty < 0 || ty >= c || g[tx][ty] == '#') continue; if (!vf[tx][ty]) { vf[tx][ty] = 1; v.x = tx; v.y = ty; v.d = u.d + 1; T[tx][ty] = v.d; qf.push(v); } } } } int bfs_man() { queue
        
          qm; while (!qm.empty()) qm.pop(); node s(sx, sy, 0); qm.push(s); memset(vm, 0, sizeof(vm)); vm[sx][sy] = 1; while (!qm.empty()) { node u = qm.front(); qm.pop(); if (u.x == 0 || u.x == r - 1 || u.y == 0 || u.y == c - 1) return u.d + 1; node v = u; for (int i = 0; i < 4; i++) { int tx = u.x + dx[i]; int ty = u.y + dy[i]; if (tx < 0 || tx >= r || ty < 0 || ty >= c || g[tx][ty] == '#') continue; if (u.d + 1 >= T[tx][ty]) continue; if (!vm[tx][ty]) { vm[tx][ty] = 1; v.x = tx; v.y = ty; v.d = u.d + 1; qm.push(v); } } } return -1; } int main() { int cas; scanf("%d", &cas); while (cas--) { scanf("%d%d", &r, &c); for (int i = 0; i < r; i++) scanf("%s", g[i]); while(!qf.empty()) qf.pop(); memset(vf, 0, sizeof(vf)); memset(T, INF, sizeof(T)); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (g[i][j] == 'J') { sx = i; sy = j; } if (g[i][j] == 'F') { node tmp(i, j, 0); vf[i][j] = 1; T[i][j] = 0; qf.push(tmp); } } } bfs_fire(); int ans = bfs_man(); if (ans == -1) printf("IMPOSSIBLE\n"); else printf("%d\n", ans); } return 0; }
        
       
      
     
    
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇如何打印斐波拉契数列以及质数列表 下一篇Codeforces 468A 24 Game(构造)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Redis 分布式锁全解 (2025-12-25 17:19:51)
·SpringBoot 整合 Red (2025-12-25 17:19:48)
·MongoDB 索引 - 菜鸟 (2025-12-25 17:19:45)
·What Is Linux (2025-12-25 16:57:17)
·Linux小白必备:超全 (2025-12-25 16:57:14)