Rescue(BFS+优先队列)
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.
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
本题需要使用BFS+优先队列。BFS查找路径,优先队列保证所走路程绝对是最短的。
ps.本题要求多组输入,英语不好,当时没注意这个问题,一直wrong answer。
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
char map[201][201]; //储存地图
int visit[201][201]; //标记走过的点
int n, m; //读取行列
int x1, y1, x2, y2; //读取初始位置和终点位置
int dir[4][2] = { {0,1},{0,-1},{1,0},{-1,0} }; //遍历右左上下四个方向
struct node
{
int x, y, k;
friend bool operator < (node a,node b) //重载运算符,保证优先队列中,总路程短的在队头
{
return a.k >b.k;
}
};
int check(int x, int y) //检查走过的点是否满足题意,即:不会走出地图,也不会有障碍物
{
if (x >= 0 && x < n && y >= 0 && y < m&&map[x][y]!='#')
return 1;
return 0;
}
int bfs()
{
node now, next;
priority_queue <node> que; //优先队列
now.x = x1;
now.y = y1;
now.k = 0;
visit[x1][y1] = 1;
que.push(now);
while (que.size())
{
now = que.top(); que.pop();
if (now.x == x2 && now.y == y2) //若走到终点则弹出优先队列中,总路程最短的那个路程。
{
return now.k;
}
for (int i = 0; i < 4; i++)
{
int x = now.x + dir[i][0];
int y = now.y + dir[i][1];
if (check(x, y))
{
if (!visit[x][y])
{
next.x = x;
next.y = y;
if(map[x][y]=='x') //核心判断,若是敌人,杀死后,路程+2
next.k=now.k+2;
else //若是普通路程,路程+1
next.k=now.k+1;
visit[x][y] = 1;
que.push(next);
}
}
}
}
return 0;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF) //这里是坑,题目要求多组输入,一开始没翻译出来。
{
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> map[i][j];
memset(visit, 0, sizeof(visit));
for (int i = 0; i < n; i++) //找出初始位置与终点位置
for (int j = 0; j < m; j++)
{
if(map[i][j]=='r')
{
x1=i;
y1=j;
}
if(map[i][j]=='a')
{
x2=i;
y2=j;
}
}
int step=bfs();
if (step)
cout << step << endl;
else
cout << "Poor ANGEL has to stay in the prison all his life." << endl;
}
return 0;
}