Rescue
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 44 Accepted Submission(s) : 13
Problem 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.<br><br>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.<br><br>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.)<br>
Input
First line contains two integers stand for N and
M.<br><br>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. <br><br>Process to the end of the file.<br>
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." <br>
Sample Input
7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........
Sample Output
13
简单题意:
求解R到达是否能到达A处,能的话,最少需要几步
思路分析:
同其他题目一样,有目标bfs了
# include <iostream> # include <cstring> # include <queue> # include <fstream> using namespace std; struct Info { int x, y; }a, r; int n, m; char map[500][500]; int dir[4][2] = {{-1, 0},{1, 0},{0, -1},{0, 1},}; int jishu[500][500]; bool border(int x, int y) { if(x >= 1 && x <= n && y >= 1 && y <= m) return true; return false; } int bfs(); int main() { //fstream cin("aaa.txt"); while(cin >> n >> m) { for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { cin >> map[i][j]; if(map[i][j] == ‘a‘) { a.x = i; a.y = j; } if(map[i][j] == ‘r‘) { r.x = i; r.y = j; } } } int haha = bfs(); if(haha == 88888888) cout << "Poor ANGEL has to stay in the prison all his life." << endl; else cout << haha << endl; } return 0; } int bfs() { for(int i = 0; i < 500; i++) for(int j = 0; j < 500; j++) jishu[i][j] = 88888888; jishu[r.x][r.y] = 0; queue <Info> Q; Q.push(r); Info t, tep; while(!Q.empty()) { tep = Q.front(); Q.pop(); if(tep.x == a.x && tep.y == a.y) { break; } for(int i = 0; i < 4; i++) { t.x = tep.x + dir[i][0]; t.y = tep.y + dir[i][1]; if(!border(t.x, t.y))// 出界, 走过, 石墙 continue; if(map[t.x][t.y] == ‘#‘) continue; int min; if(map[t.x][t.y] == ‘x‘) min = jishu[tep.x][tep.y] + 2; else min = jishu[tep.x][tep.y] + 1; if(min >= jishu[t.x][t.y]) continue; jishu[t.x][t.y] = min; //cout << jishu[t.x][t.y] << endl; Q.push(t); } } return jishu[a.x][a.y]; }