直接贴代码好了。。。感觉Bfs的重点只是在于理清
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
using namespace std;
int n,m,cont;
char mp[105][105]; //记录地图
struct
{
int x,y,d;
int before;
}q[10000007],s,now;
bool vis[105][105];
int xx,yy;
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0}; //方向数组
bool judge(int x,int y)
{
if(x>=0 && x<n && y>=0 && y<m && mp[x][y]!='X') return true;
return false;
} //判定墙壁和出界
void print(int n)
{
if(q[n].before==-1)
{
xx=0;
yy=0;
return;
}
print(q[n].before);
printf("%ds:",cont++);
if(xx==q[n].x && yy==q[n].y) printf("FIGHT AT (%d,%d)\n",xx,yy);
else
{
printf("(%d,%d)->(%d,%d)\n",xx,yy,q[n].x,q[n].y);
xx=q[n].x;
yy=q[n].y;
}
} //利用Dfs寻找路径
void Bfs() //用Bfs找出最佳路径
{
int head=0;
int tail=0;
q[tail++]=s;
vis[0][0]=1;
while(tail>head)
{
now=q[head++];
//cout<<now.x<<" "<<now.y<<endl;
//system("pause");
if(mp[now.x][now.y]!='.' && mp[now.x][now.y]!='0')
{
mp[now.x][now.y]--;
q[tail]=now;
q[tail].before=head-1;
q[tail].d++;
tail++;
continue;
}
if(now.x==n-1 && now.y==m-1)
{
printf("It takes %d seconds to reach the target position, let me show you the way.\n",now.d);
print(head-1);
return;
}
for(int i=0;i<4;i++)
{
int x=now.x+dx[i],y=now.y+dy[i];
if(!vis[x][y] && judge(x,y))
{
q[tail].x=x;
q[tail].y=y;
q[tail].d=now.d+1;
q[tail++].before=head-1;
vis[x][y]=1;
}
}
}
printf("God please help our poor hero.\n");
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i=0;i<n;i++)
{
scanf("%s",mp[i]);
memset(vis[i],0,sizeof vis[i]);
}
//初始化
cont=1;
s.x=0;
s.y=0;
s.d=0;
s.before=-1;
Bfs();
printf("FINISH\n");
}
return 0;
}