http://acm.hdu.edu.cn/showproblem.php?pid=1242
该题可能有多个r点,但只有一个a点,所以从a开始搜索。因为道路上有两种情况,当步数相同时所耗时间可能不同,而最后要求最短时间,所以应按时间小优先而不是步数少优先。
#include<stdio.h>
#include<queue>
#define N 202
using namespace std;
int flag[N][N],n,m,x,y,i,j,ans;
int dir[4][2]={0,1,1,0,0,-1,-1,0};
struct node
{
friend bool operator<(node a,node b)
{
return a.time>b.time;
}
int x,y,time;
};
int BFS(int a,int b)
{
priority_queue<node>q;
node now,next;
now.x=x;now.y=y;now.time=0;
q.push(now);
while(!q.empty())
{
now=q.top();
q.pop();
for(i=0;i<4;i++)
{
next.x=now.x+dir[i][0];
next.y=now.y+dir[i][1];
next.time=now.time+1;
if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&flag[next.x][next.y]!=0)
{
if(flag[next.x][next.y]==3)
return next.time;
if(flag[next.x][next.y]==2)
next.time++;
flag[next.x][next.y]=0;
q.push(next);
}
}
}
return -1;
}
int main()
{
char t;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=0;i<n;i++)
{
getchar();
for(j=0;j<m;j++)
{
scanf("%c",&t);
if(t=='#')
flag[i][j]=0;
if(t=='.')
flag[i][j]=1;
if(t=='x')
flag[i][j]=2;
if(t=='r')
flag[i][j]=3;
if(t=='a')
{
x=i;
y=j;
}
}
}
ans=BFS(x,y);
if(ans!=-1)
printf("%d\n",ans);
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}
分享到:
相关推荐
hdu acm 教案 搜索入门 hdu acm 教案 搜索入门
杭州电子科技大学oj平台上的第1010题,是关于搜索的题目,很不错的题
搜索 dfs 解题代码 hdu1241
HDUACM201303版_10搜索入门
HDU的1250,主要是利用高精度加法,但是代码有点繁琐,效率不是很高
杭电ACMhdu1163
HDU1059的代码
hdu1001解题报告
hdu 1574 passed sorce
HDU的一题........HDU DP动态规
hdu2101AC代码
hdu 5007 Post Robot 字符串枚举。 暴力一下就可以了。
hdu acm 教案 动态规划(1) hdu acm 教案 动态规划(1)
hdu 1166线段树代码
ACM HDU题目分类,我自己总结的大概只有十来个吧
自己做的HDU ACM已经AC的题目
HDU最全ac代码
hdu动态规划算法集锦
hdu题目分类