hdu 1242 BFS

来源:互联网 发布:剑三苍云成男脸型数据 编辑:程序博客网 时间:2024/04/26 17:27

注意 这题用a 来搜r 注意了!!!

AC代码如下:

#include <iostream>#include <cstdio>#include <cstring>#include <vector>#include <queue>using namespace std;typedef struct{int x, y;int time;}Node;int N, M;int moves[4][2] = { 1, 0, -1, 0, 0, -1, 0, 1 };int map[200][200];bool visit[200][200];vector<Node> friends;Node angle;void init(){memset( visit, false, sizeof( visit ) );friends.clear();}int BFS( Node start ){memset( visit, false, sizeof( visit ) );queue<Node> q;start.time = 0;q.push( start );while( !q.empty() ){Node n = q.front();q.pop();for( int i = 0; i < friends.size(); i++ ){if( n.x == friends[i].x && n.y == friends[i].y ){return n.time;}}for( int i = 0; i < 4; i++ ){Node temp = n;temp.x += moves[i][0];temp.y += moves[i][1];if( temp.x < 0 || temp.x >= N || temp.y < 0 || temp.y >= M ){continue;}if( map[temp.x][temp.y] == 0 ){continue;}if( visit[temp.x][temp.y] == true ){continue;}temp.time += map[temp.x][temp.y];visit[temp.x][temp.y] = true;q.push( temp );}}return -1;}int main(){char s[201];while( scanf( "%d%d", &N, &M ) != EOF ){init();for( int i = 0; i < N; i++ ){scanf( "%s", s );for( int j = 0; j < M; j++ ){if( s[j] == 'r' ){map[i][j] = 1;Node temp;temp.x = i;temp.y = j;friends.push_back( temp );}else if( s[j] == '.' ){map[i][j] = 1;}else if( s[j] == 'x' ){map[i][j] = 2;}else if( s[j] == 'a' ){map[i][j] = 1;angle.x = i;angle.y = j;}else{map[i][j] = 0;}}}int ans = BFS( angle );if( ans != -1 ){cout << ans << endl;}else{cout << "Poor ANGEL has to stay in the prison all his life." << endl;}} return 0;}