G - BFS广搜

来源:互联网 发布:sqlserver 2008 2012 编辑:程序博客网 时间:2024/04/28 12:20

G - BFS广搜
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Submit Status Practice HDU 1242

Description

Angel was caught by the MOLIGPY! He was put in prison by Moligpy. The prison is described as a N * M (N, M <= 200) matrix. There are WALLs, ROADs, and GUARDs in the prison. 

Angel's friends want to save Angel. Their task is: approach Angel. We assume that "approach Angel" is to get to the position where Angel stays. When there's a guard in the grid, we must kill him (or her?) to move into the grid. We assume that we moving up, down, right, left takes us 1 unit time, and killing a guard takes 1 unit time, too. And we are strong enough to kill all the guards. 

You have to calculate the minimal time to approach Angel. (We can move only UP, DOWN, LEFT and RIGHT, to the neighbor grid within bound, of course.) 
 

Input

First line contains two integers stand for N and M. 

Then N lines follows, every line has M characters. "." stands for road, "a" stands for Angel, and "r" stands for each of Angel's friend. 

Process to the end of the file. 
 

Output

For each test case, your program should output a single integer, standing for the minimal time needed. If such a number does no exist, you should output a line containing "Poor ANGEL has to stay in the prison all his life." 
 

Sample Input

7 8#.#####.#.a#..r.#..#x.....#..#.##...##...#..............
 

Sample Output

13
 

PS:广搜,标记r到a时所有情况,a点存步数最小的。

代码:

#include<iostream>#include<string>#include<queue>using namespace std;struct P{int x;int y;int count;}pr,pa, p;char map[210][210];int dis[210][210];queue<P> prs;int cou = 99999;int n, m;int f[4][2] = { 0, 1, 1, 0, -1, 0, 0, -1 };void bfs(){while (!prs.empty()){pr = prs.front();prs.pop();if (pr.x == pa.x && pr.y == pa.y){if (cou > pr.count){cou = pr.count;}}else{for (int i = 0; i < 4; ++i){p.x = pr.x + f[i][0];p.y = pr.y + f[i][1];p.count = pr.count + 1;if (p.x >= 0 && p.x < n && p.y >= 0 && p.y < m && map[p.x][p.y] != '#' && p.count < dis[p.x][p.y]){if (map[p.x][p.y] == 'x'){p.count++;}if (dis[p.x][p.y] > p.count){dis[p.x][p.y] = p.count;}prs.push(p);}}}}}int main(){while (cin >> n >> m){cou = 99999;for (int i = 0; i < n; ++i){for (int j = 0; j < m; ++j){dis[i][j] = 99999;cin >> map[i][j];if (map[i][j] == 'a'){pa.x = i;pa.y = j;}else if (map[i][j] == 'r'){pr.x = i;pr.y = j;pr.count = 0;prs.push(pr);}}}bfs();if (cou == 99999){cout << "Poor ANGEL has to stay in the prison all his life." << endl;}else{cout << cou << endl;}}return 0;}




0 0
原创粉丝点击