hdu 1026 Ignatius and the Princess I bfs

用到了图论最短路更新的思想,当走到走过的地方时要更新

数据:

5 6

.XX.1.

..X.6.

2...X.

...XX.

XXXXX.

View Code
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;

struct node{
int x,y,num,t;
}a;

struct Path{
int x,y,pre,fight;
}p[500000];

int n,m,k,l,key,dp[105][105];
char map[105][105];

void f(int z)
{
int i;
if(z)
{
f(p[z].pre);
printf("%ds:(%d,%d)->(%d,%d)\n",l++,p[p[z].pre].x,p[p[z].pre].y,p[z].x,p[z].y);
for (i=0;i<p[z].fight;i++)
printf("%ds:FIGHT AT (%d,%d)\n",l++,p[z].x,p[z].y);
}
}

void bfs()
{
int i,row,col,time,dir[4][2]={0,1,1,0,-1,0,0,-1};
queue<node> q;
q.push(a);
while (!q.empty())
{
a=q.front();q.pop();
for (i=0;i<4;i++)
{
row=dir[i][0]+a.x;
col=dir[i][1]+a.y;
if(row>=0&&col>=0&&row<n&&col<m&&map[row][col]!='X')
{
if(map[row][col]=='.')time=1;
else time=map[row][col]-'0'+1;
if(dp[row][col]>a.t+time)
{
if(row==n-1&&col==m-1)key=k;
dp[row][col]=a.t+time;
p[k].pre=a.num;
p[k].x=row;
p[k].y=col;
p[k].fight=time-1;
node b;
b.x=row;
b.y=col;
b.num=k++;
b.t=a.t+time;
q.push(b);
}
}
}
}
}

int main()
{
int i,j;
while (scanf("%d%d",&n,&m)!=EOF)
{
for (i=0;i<n;i++)
{
for (j=0;j<m;j++)
dp[i][j]=0x3f3f3f3f;
}
dp[0][0]=0;
for (i=0;i<n;i++)scanf("%s",map[i]);
a.x=a.y=a.num=a.t=0;
k=l=1;
memset(p,0,sizeof(p));
bfs();
if(dp[n-1][m-1]==0x3f3f3f3f)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",dp[n-1][m-1]);
f(key);
}
printf("FINISH\n");
}
return 0;
}



posted @ 2011-12-22 14:34  104_gogo  阅读(98)  评论(0编辑  收藏  举报