题目链接;
http://acm.hdu.edu.cn/showproblem.php?pid=1242
解析:
我是反着做,多个朋友找天使,就是用优先队列按步数排序BFS
而更简单的办法是一个天使找朋友DFS,这样其实就是最简单的dfs
BFS:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
#define MAXN 300
#define inf 999999999
typedef struct local
{
int x,y;
int time;
friend bool operator <(local n1,local n2)
{
return n1.time>n2.time;
}
}loca;
loca direction[4]={{1,0},{0,1},{-1,0},{0,-1}};
char map[MAXN][MAXN];
int visit[MAXN][MAXN];
loca start[MAXN];
int n,m,ans,num;
int check(int x,int y)
{
if(map[x][y]!='#'&&visit[x][y]==0&&x>=1&&x<=n&&y>=1&&y<=m)
return 1;
else
return 0;
}
void BFS()
{
priority_queue<loca>step;
int i;
loca oth;
for(i=0;i<num;i++)
{
visit[start[i].x][start[i].y]=1;
step.push(start[i]);
}
while(step.size())
{
oth=step.top();
if(map[oth.x][oth.y]=='a'&&ans>oth.time)
{
ans=oth.time;
break;
}
step.pop();
int x,y;
loca tmp;
for(i=0;i<4;i++)
{
x=oth.x+direction[i].x;
y=oth.y+direction[i].y;
if(check(x,y))
{
if(map[x][y]=='x')
{
tmp.x=x;
tmp.y=y;
tmp.time=oth.time+2;
visit[tmp.x][tmp.y]=1;
step.push(tmp);
}
else
{
tmp.x=x;
tmp.y=y;
tmp.time=oth.time+1;
visit[tmp.x][tmp.y]=1;
step.push(tmp);
}
}
}
}
}
int main()
{
int i,j,s1,s2;
while(scanf("%d%d",&n,&m)!=EOF)
{
num=0;
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
cin>>map[i][j];
if(map[i][j]=='r') //注意有多个起点
{
start[num].x=i;
start[num].y=j;
start[num].time=0;
num++;
}
}
}
memset(visit,0,sizeof(visit));
ans=inf;
BFS();
if(ans!=inf) printf("%d\n",ans);
else printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}
DFS:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <climits>
const int MAX = 202;
char map[MAX][MAX];
int visit[MAX][MAX];
int n,m,ax,ay,minx;
void dfs(int x,int y,int len){
if(x<0 || y<0 || x>=n || y>=m)return;
if(len>=minx)return;
if(map[x][y]=='#')return;
if(visit[x][y]==1)return;
if(map[x][y]=='r'){
if(len<minx)minx=len;
return;
}
if(map[x][y]=='x'){
++len;
}
visit[x][y]=1;
dfs(x+1,y,len+1);
dfs(x-1,y,len+1);
dfs(x,y+1,len+1);
dfs(x,y-1,len+1);
visit[x][y]=0;
}
int main(){
//freopen("in.txt","r",stdin);
int i,j,len;
while(scanf("%d %d%*c",&n,&m)!=EOF){
for(i=0;i<n;++i){
for(j=0;j<m;++j){
map[i][j]=getchar();
if(map[i][j]=='a'){
ax = i;
ay = j;
}
}
getchar();
}
len = 0;
minx = INT_MAX;
dfs(ax,ay,len);
if(minx!=INT_MAX){
printf("%d\n",minx);
}else{
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
}
return 0;
}