http://acm.hdu.edu.cn/showproblem.php?pid=1242
用bfs做,要用优先队列
#include<iostream>
#include<string>
#include<queue>
using namespace std;
int sx,sy,ex,ey;
int n,m;
int map[205][205];
int dis[4][2]={0,1,1,0,0,-1,-1,0};
struct node{
int x,y;
int step;
friend bool operator<(node a,node b) //优先队列必须写的
{
return b.step<a.step;
}
};
bool cmp(int a,int b) //判断函数
{
if(a<0||a>=n||b<0||b>=m) return 1;
if(map[a][b]==1) return 1;
return 0;
}
int bfs()
{
priority_queue<node>q; //优先队列的申明
node cur,next;
int i;
cur.x=sx;
cur.y=sy;
cur.step=0;
map[cur.x][cur.y]=1;
q.push(cur);
while(!q.empty())
{
cur=q.top();
if(cur.x==ex&&cur.y==ey) return cur.step; //如果到达出口就跳出
q.pop();
for(i=0;i<4;i++) //往四个方向进行搜索
{
next.x=cur.x+dis[i][0];
next.y=cur.y+dis[i][1];
if(cmp(next.x,next.y)) continue ;
if(map[next.x][next.y]==-1) next.step=cur.step+2;
else next.step=cur.step+1;
map[next.x][next.y]=1;
q.push(next);
}
}
return 0;
}
int main()
{
int i,j;
int a,b;
char str;
while(cin>>n>>m)
{
memset(map,0,sizeof(map)); //一定要初始化
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
cin>>str;
if(str=='a') {sx=i;sy=j;} //朋友可能有多个,所以从天使开始搜索
else if(str=='r') {ex=i;ey=j;}
else if(str=='x') {map[i][j]=-1;}
else if(str=='.') {map[i][j]=0;}
else if(str=='#') {map[i][j]=1;}
}
}
int sum=bfs();
if(sum==0) cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
else cout<<sum<<endl;
}
return 0;
}