1.题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1242
2.思路:
这道题目可以用深搜或者广搜来做。要注意的是天使的朋友不止一个,所以应当从天使出发,目标是在最短的时间里找到天使的朋友,然后营救天使。
3.参考代码一(dfs):
#include <stdio.h>
#include <string.h>
#define inf 0xffff
int n,m,flag,count;
int si,sj,ei,ej;
int map[300][300];
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
void dfs(int x,int y,int t){
int i,qx,qy;
if(x==ei && y==ej)
{
flag=1;
if(count>t)
count=t;
return ;
}
for(i=0;i<4;i++)
{
qx=x+dir[i][0];
qy=y+dir[i][1];
if(map[qx][qy]!='#' && qx>=0 && qx<n && qy>=0 && qy<m)
{
if(map[qx][qy]=='x')
{
map[qx][qy]='#';
dfs(qx,qy,t+2);
map[qx][qy]='x';
}
else
{
map[qx][qy]='#';
dfs(qx,qy,t+1);
map[qx][qy]='.';
}
}
}
}
int main()
{
int i,j;
while(~scanf("%d %d%*c",&n,&m))
{
flag=0;
count=inf;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf("%c",&map[i][j]);
if(map[i][j]=='a')
{
si=i;
sj=j;
}
else if(map[i][j]=='r')
{
ei=i;
ej=j;
}
}
getchar();
}
dfs(si,sj,0);
if(flag)
printf("%d\n",count);
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}
参考代码二(bfs):
#include <stdio.h>
#include <queue>
#include <string.h>
using namespace std; ///这个一定要加
int n,m;
int sx,sy,ex,ey;
char map[300][300];
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
struct Node{
int x,y;
int step;
friend bool operator<(Node n1,Node n2){
return n2.step<n1.step;
}
};
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();
q.pop();
if(cur.x==ex && cur.y==ey)
return cur.step;
for(i=0;i<4;i++)
{
next.x=cur.x+dir[i][0];
next.y=cur.y+dir[i][1];
if(map[next.x][next.y]==1 || next.x<0 || next.x>=n || next.y<0 || next.y>=m)
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 -1;
}
int main()
{
int i,j,ans;
char str[300];
while(~scanf("%d%d%*c",&n,&m))
{
memset(map,0,sizeof(map));
for(i=0;i<n;i++)
{
scanf("%s",str); ///这里是str而不是str[i]
for(j=0;j<m;j++)
{
if(str[j]=='r')
{
sx=i;
sy=j;
}
else if(str[j]=='a')
{
ex=i;
ey=j;
}
else if(str[j]=='#')
map[i][j]=1;
else if(str[j]=='.')
map[i][j]=0;
else if(str[j]=='x')
map[i][j]=-1;
}
}
ans=bfs();
if(ans==-1)
printf("Poor ANGEL has to stay in the prison all his life.\n");
else
printf("%d\n",ans);
}
return 0;
}