您的位置:首页 > 其它

hdu 1026 Ignatius and the Princess I(BFS)

2013-11-22 12:33 537 查看
只需要记录路径就行了,对于花费的时间,可以用优先队列来维护。难得的1A。

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
#define N 105
int mark

,vis

;
int n,m;
char s
;
int cnt;
int dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}};
struct node
{
int x,y;
int cnt;
friend bool operator<(node a,node b)
{
return a.cnt>b.cnt;
};
}q[N*N];
struct point
{
int prex,prey;
}ans

;
int judge(int x,int y)
{
if(x>=1&&x<=m&&y>=1&&y<=n&&mark[x][y]!=-1&&vis[x][y]==0) return 1;
return 0;
}
int BFS()
{
node cur,next;
cur.x=1;cur.y=1;cur.cnt=0;vis[1][1]=1;
priority_queue<node>q;
q.push(cur);
while(!q.empty())
{
cur=q.top();
q.pop();
for(int i=0;i<4;i++)
{
next.cnt=cur.cnt+1;
next.x=cur.x+dir[i][0];
next.y=cur.y+dir[i][1];
if(judge(next.x,next.y))
{
if(mark[next.x][next.y]!=0) next.cnt+=mark[next.x][next.y];
vis[next.x][next.y]=1;
ans[next.x][next.y].prex=cur.x;ans[next.x][next.y].prey=cur.y;
if(next.x==m&&next.y==n) return next.cnt;
q.push(next);
}
}
}
return -1;
}
void print(int x,int y)
{
if(x==1&&y==1) return ;
print(ans[x][y].prex,ans[x][y].prey);
printf("%ds:(%d,%d)->(%d,%d)\n",cnt++,ans[x][y].prex-1,ans[x][y].prey-1,x-1,y-1);
if(mark[x][y]==0) return ;
while(mark[x][y]--) printf("%ds:FIGHT AT (%d,%d)\n",cnt++,x-1,y-1);
return ;
}
int main()
{
while(scanf("%d%d",&m,&n)!=EOF)
{
getchar();
for(int i=1;i<=m;i++)
{
gets(s+1);
for(int j=1;j<=n;j++)
{
if(s[j]=='.') mark[i][j]=0;
else if(s[j]=='X') mark[i][j]=-1;
else mark[i][j]=s[j]-'0';
}
}
int answer;
memset(vis,0,sizeof(vis));
memset(ans,0,sizeof(ans));
answer=BFS();
if(answer==-1) printf("God please help our poor hero.\n");
else
{
printf("It takes %d seconds to reach the target position, let me show you the way.\n",answer);
cnt=1;
print(m,n);
}
printf("FINISH\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: