UVa 11624 Fire! / BFS

來源:互聯網
上載者:User

和普通BFS相比 多了個火

那麼先對火做一次BFS 預先處理每個格子著火的時間

偷懶了 少開個數組 然後錯了半天

#include <algorithm>#include <cstring>#include <queue>#include <cstdio>using namespace std;const int MAX = 1010;char a[MAX][MAX];int map[MAX][MAX];struct node{int x;int y;int t;}s;int n, m;int dir[4][2] = {1,0,-1,0,0,1,0,-1};bool bfs(){queue <node> f;queue <node> q;memset(map,-1,sizeof(map));int i, j;for(i = 0; i < n; i++){for(j = 0; j < m; j++){if(a[i][j] == 'F'){node t;t.x = i;t.y = j;t.t = 0;f.push(t);map[i][j] = 0;}else if(a[i][j] == 'J'){node t;t.x = i;t.y = j;t.t = 0;q.push(t);}}}while(!f.empty()){node u = f.front();f.pop();for(i = 0; i < 4; i++){node t;t.x = u.x + dir[i][0];t.y = u.y + dir[i][1];t.t = u.t + 1;if(t.x >= 0 && t.x < n && t.y >= 0 && t.y < m && a[t.x][t.y] != '#' && map[t.x][t.y] == -1){map[t.x][t.y] = t.t;f.push(t);}}}/*for(i = 0;i < n; i++){for(j = 0;j < m; j++)printf("%d ",map[i][j]);puts("");}*/while(!q.empty()){node u = q.front();q.pop();for(i = 0; i < 4; i++){node t;t.x = u.x + dir[i][0];t.y = u.y + dir[i][1];t.t = u.t + 1;if(t.x < 0 || t.x >= n || t.y < 0 || t.y >= m){printf("%d\n",t.t);return true;}if(t.x >= 0 && t.x < n && t.y >= 0 && t.y < m && a[t.x][t.y] != '#' && (map[t.x][t.y] > t.t || map[t.x][t.y] == -1)){a[t.x][t.y] = '#';q.push(t);}}}return false;}int main(){int cas;int i, j;scanf("%d",&cas);while(cas--){scanf("%d %d",&n,&m);for(i = 0; i < n; i++)scanf("%s",a[i]);if(!bfs())printf("IMPOSSIBLE\n");}return 0;}


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.