/* Function Description: HDOJ 1242
Environment: DEV C++ 5.6.3.1
Technique:
Version:
Author: valar morghulis
Date: 20150806
Notes:正难则反,只有一个公主,但有好多‘男人’来救她。。。
不但用到优先队列,还是经典的广搜题,BFS经典题目哦
可以看出来题中输入数据的x代表守卫,#代表墙,a是美丽的小公主,r是勇士们
7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........
*/
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
char map[201][201];//The array (stand for PRISON)
int M,N,direction[4][2]={ {1,0},{-1,0}, {0,1},{0,-1}};
struct node//dingyi youxianduilie in jiegouti
{
int x;
int y;
int step;
friend bool operator<(node x, node y)//don't forget the '<' hui error de!
{
return x.step > y.step;
}
};
void bfs(node);
int main()
{
node start;
while(~scanf("%d%d",&N,&M))
{
for(int i=1;i<=N;i++)
{
getchar();//absorb the plank
for(int j=1;j<=M;j++)
{
scanf("%c",&map[i][j]);
if(map[i][j]=='a')
{
start.x=i;
start.y=j;
start.step=0;
//
}
}
}
bfs(start);
}
return 0;
}
void bfs(node x)
{
node a,b;
priority_queue <node> q;//you xian dui lie
q.push(x);//first yuansu jin duiwu
while(!q.empty())
{
a=q.top();//top yuansu chudui jie shou zhemo~~
q.pop();//at the same time qingkong zhege position leave next yuansu
for(int i=0;i<4;i++)//yicentyiceng de xunhuan search zhe jiu shi BFS de character
{
b.x=a.x+direction[i][0];//direction up&&down
b.y=a.y+direction[i][1];//direction left && right
b.step=a.step+1;
if(b.x<1||b.y<1||b.x>N||b.y>M||map[b.x][b.y]=='#')
continue ;
if(map[b.x][b.y]=='x')
b.step++;
if(map[b.x][b.y]=='r')
{
printf("%d\n",b.step);
return;
}
map[b.x][b.y]='#';
q.push(b);
}
}
printf("Poor ANGEL has to stay in the prison all his life.\n");
return ;
}
最近纠结BFS算法几天了,简直不能自拔;RESCURE这道题虽然不是很复杂,可其中的BFS思想还是很经典了,尤其是在for循环那块,你能很清晰的体会到BFS算法的分层循环、由近及远的思想。