题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1026
#include<iostream>
#include<string>
#include<queue>
using namespace std;
struct point
{
int x,y;
int pDir[500];
int st;
}p;
int dir[4][2]={1,0,0,1,-1,0,0,-1};
int n,m;
int map[102][102];
int t[102][102];
bool isval(int a,int b)
{
if(a<0||b<0||a>=n||b>=m)return false;
if(map[a][b]==-1)return false;
return true;
}
void priBfs()
{
int i,x=0,y=0;
for(i=0;i<t[n-1][m-1];i++)
{
if(p.pDir[i]!=-1)
{
printf("%ds:(%d,%d)",i+1,x,y);
x+=dir[p.pDir[i]][0];
y+=dir[p.pDir[i]][1];
printf("->(%d,%d)\n",x,y);
}
else printf("%ds:FIGHT AT (%d,%d)\n",i+1,x,y);
}
}
void makemax()
{
int i,j;
for(i=0;i<102;i++)
for(j=0;j<102;j++)
t[i][j]=INT_MAX;
}
void bfs()
{
queue<point> min;
makemax();
t[0][0]=0;
struct point s;
s.x=0;
s.y=0;
s.st=0;
memset(s.pDir,-1,sizeof(s.pDir));
min.push(s);
while(!min.empty())
{
struct point temp;
temp=min.front();
s=temp;//这个要注意的
min.pop();
int i;
for(i=0;i<4;i++)
{
s.x=temp.x+dir[i][0];
s.y=temp.y+dir[i][1];
if(isval(s.x,s.y))
{
s.st=temp.st+map[s.x][s.y]+1;
if(s.st<t[s.x][s.y])
{
s.pDir[temp.st]=i;
if(s.x==n-1&&s.y==m-1&&t[n-1][m-1]>s.st)p=s;
t[s.x][s.y]=s.st;
min.push(s);
}
}
}
}
if(t[n-1][m-1]==INT_MAX)
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",t[n-1][m-1]);
priBfs();
}
printf("FINISH\n");
}
int main()
{
while(scanf("%d %d",&n,&m)!=EOF)
{
int i,j;
for(i=0;i<n;i++)
{
getchar();
for(j=0;j<m;j++)
{
char c;
scanf("%c",&c);
if(c=='X')map[i][j]=-1;
else if(c=='.')map[i][j]=0;
else map[i][j]=c-'0';
}
}
bfs();
}
return 0;
}