7 8 #.#####. #.a#..r. #..#x... ..#..#.# #...##.. .#...... ........
13
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<queue>
#include<string>
using namespace std;
struct s
{
int x,y,w;
friend bool operator <(s a,s b)
{
return a.w>b.w;
}
}a,temp;
int dx[4]={0,-1,0,1};
int dy[4]={-1,0,1,0},n,m,sx,sy;
char map[1010][1010];
bool vis[1010][1010];
int jud(struct s a)
{
if(a.x<0||a.x>=n||a.y<0||a.y>=m)
return 0;
if(vis[a.x][a.y])
return 0;
if(map[a.x][a.y]=='#')
return 0;
return 1;
}
int bfs()
{
memset(vis,false,sizeof(vis));
a.x=sx;
a.y=sy;
a.w=0;
priority_queue<struct s>q;
vis[sx][sy]=true;
q.push(a);
while(!q.empty())
{
a=q.top();
q.pop();
for(int i=0;i<4;i++)
{
temp.x=a.x+dx[i];
temp.y=a.y+dy[i];
if(!jud(temp))
continue;
if(map[temp.x][temp.y]=='x')
temp.w=a.w+2;
else
temp.w=a.w+1;
if(map[temp.x][temp.y]=='r')
{
return temp.w;
}
vis[temp.x][temp.y]=1;
q.push(temp);
}
}
return -1;
}
int main()
{
//int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
int i,j;
for(i=0;i<n;i++)
{
scanf("%s",map[i]);
for(j=0;j<m;j++)
{
if(map[i][j]=='a')
{
sx=i;
sy=j;
}
}
}
int ans=bfs();
if(ans==-1)
{
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
else
printf("%d\n",ans);
}
}原文:http://blog.csdn.net/yu_ch_sh/article/details/44595255