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.)
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.
题解:广搜,每次找时间最短的一个,因为遇到士兵时间多1,此时这个点应该排在后面。所以用优先队列排序。
#include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; struct Node { int x; int y; int time; Node(int a,int b,int c) { x = a; y = b; time = c; } bool operator< (Node t) const { return time > t.time; } }; int sx,sy; int n,m; int ans; char map[205][205]; int d[4][2] = {{0,-1},{0,1},{-1,0},{1,0}}; bool bfs() { priority_queue<Node> q; q.push(Node(sx,sy,0)); ans = 0; map[sx][sy] = '#'; while(!q.empty()) { Node p = q.top(); q.pop(); for(int i = 0;i < 4;i++) { int x = p.x + d[i][0]; int y = p.y + d[i][1]; if(x >= 0 && x < n && y >= 0 && y < m && map[x][y] != '#') { if(map[x][y] == 'a') { ans = p.time + 1; return true; } if(map[x][y] == 'x') { q.push(Node(x,y,p.time + 2)); } else { q.push(Node(x,y,p.time + 1)); } map[x][y] = '#'; } } } return false; } int main() { while(scanf("%d%d",&n,&m) != EOF) { getchar(); for(int i = 0;i < n;i++) { for(int j = 0;j < m;j++) { scanf("%c",&map[i][j]); if(map[i][j] == 'r') { sx = i; sy = j; } } getchar(); } if(bfs()) { printf("%d\n",ans); } else { printf("Poor ANGEL has to stay in the prison all his life.\n"); } } return 0; }