#include<iostream> #include<string> #include<queue> #include<stdio.h> using namespace std; struct point { int x,y,step; }p; string map[211]; int used[211][211]; int f[4][2] = {{1,0},{0,1},{-1,0},{0,-1}}; int n,m; queue<point> q; int bfs() { int step = 0,i,l = 1,t = 0,t0 = 0; point p1; while(!q.empty()) { t++; p = q.front(); q.pop(); if(p.step > step) { q.push(p);t0++;} else{ for(i = 0; i < 4; i++) { p1.x = p.x + f[i][0]; p1.y = p.y + f[i][1]; if(p1.x >=0&&p1.x<n&&p1.y>=0&&p1.y<m&&map[p1.x][p1.y] != ‘#‘) { if(map[p1.x][p1.y] == ‘.‘) p1.step = p.step+1; else if(map[p1.x][p1.y] == ‘x‘) p1.step = p.step + 2; else { // cout<<p.x<<‘ ‘<<p.y<<‘ ‘<<p.step<<endl; // cout<<p1.x<<‘ ‘<<p1.y<<‘ ‘<<p1.step<<endl; // cout<<map[p1.x][p1.y]<<endl; return p.step+1; } map[p1.x][p1.y] = ‘#‘; q.push(p1);t0++; } } } if(l == t) { l = t0; t0 = 0;t = 0; step++; // cout<<l<<endl; } // step++; // cout<<step<<endl; } return -1; } int main() { while(cin>>n>>m) { // memset(used,0,sizeof(map)); int i,j; getchar(); for(i = 0; i < n; ++i){ cin>>map[i]; if(!q.empty())continue; for(j = 0; j < m; ++j){ if(map[i][j] == ‘r‘) { map[i][j] = ‘#‘; p.x = i;p.y = j;p.step = 0; q.push(p);break; } } } int total = bfs(); if(total == -1) cout<<"Poor ANGEL has to stay in the prison all his life."<<endl; else cout<<total<<endl; while(!q.empty()) { q.pop(); } // for(i = 0; i < n; ++i) // cout<<s[i]<<endl; } return 0; } /* 7 8 #.#####. #.a#..r. #..#x... ..#xx#.# #...##.. .#...... ........ */
原文:http://www.cnblogs.com/2014acm/p/3899833.html