之前用dfs剪枝AC了,http://www.cnblogs.com/ediszhao/p/4741825.html,这次用bfs+priority_queue来尝试解题
题意:拯救行动,天使r有多个朋友a(friends,在这里被坑了几次,没看清题意),天使被关在牢房里,等着朋友来拯救,求拯救天使的最短距离。
以天使为起点进行bfs,找到的a就是最小拯救时间值。
#include <iostream>
#include <cstring>
#include <queue> using namespace std; struct node
{
int x,y,cnt;
friend bool operator < (node a,node b)
{
return a.cnt > b.cnt;
}
};
const int M = ;
char map[M][M];
int visited[M][M];
int n,m; int dire[][] = {{,},{,},{-,},{,-}};
priority_queue <struct node> q;
int bfs()
{
node now,next;
while (!q.empty())
{
now = q.top();
q.pop();
for (int i = ; i< ; i++)
{
int x = now.x+dire[i][];
int y = now.y+dire[i][];
if (x >= && x < n && y >= && y < m && map[x][y]!='#' && visited[x][y] == )
{
next.x = x;
next.y = y;
if (map[x][y] == 'a')
{
return (now.cnt+);
}
if (map[x][y] == 'x')
{
next.cnt = now.cnt+;
}
else next.cnt = now.cnt+;
visited[x][y] = ;
q.push(next);
}
}
}
return ;
}
int main()
{
while (cin >> n >> m)
{
node nn;
while (!q.empty()) //一定要清空之前的队列,在这里wrong了
q.pop();
for (int i =; i < n; i++)
{
for (int j = ; j < m; j++)
{
cin >> map[i][j];
visited[i][j] = ;
if (map[i][j] == 'r')
{
nn.x = i;
nn.y = j;
nn.cnt = ;
q.push(nn);
visited[i][j] = ;
}
}
}
int res = bfs();
if (!res)
cout << "Poor ANGEL has to stay in the * all his life.\n";
else cout << res << endl;
}
return ;
} /*
7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........
2 8
a.#####r
#..xxaxx
*/