感觉自己还有好长好长的路要走。。
考察:bfs时用到队列找到最优路线,用栈存储经过的点并输出。
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
typedef struct point
{
int x,y,cost,prex,prey;
}point;//点结构体,包含当前点的坐标以及前一点的坐标和到这个点所需要的时间
char map[105][105];
point p[105][105];
int dir[4][2]={-1,0,1,0,0,-1,0,1};
int n,m;
bool open(int x,int y)//判断是否能够通行
{
if(x<n&&x>=0&&y<m&&y>=0&&map[x][y]!='X')
return 1;
else
return 0;
}
void printpath(int x,int y)//利用栈来存储路径,并输出
{
stack<point>s;
int i=1,j;
point a,b;
cout<<"It takes "<<p[n-1][m-1].cost<<" seconds to reach the target position,let me show you the way."<<endl;
a=p[x][y];
while(1)
{
if(a.x==0&&a.y==0)break;
s.push(a);
a=p[a.prex][a.prey];
}
a=p[0][0];
while(!s.empty())
{
b=s.top();
s.pop();
if(map[b.x][b.y]=='.')
{
cout<<i++<<"s:("<<a.x<<","<<a.y<<")->("<<b.x<<","<<b.y<<")"<<endl;
}
else
{
j=map[b.x][b.y]-'0';
cout<<i++<<"s:("<<a.x<<","<<a.y<<")->("<<b.x<<","<<b.y<<")"<<endl;
while(j--)
cout<<i++<<"s:FIGHT AT ("<<b.x<<","<<b.y<<")"<<endl;
}
a=b;
}
cout<<"FINISH"<<endl;
}
int bfs(int x,int y)//利用队列进行bfs,为p[][]赋值,找到最优路线
{
queue<point>que;
point a,b;
int i,j;
a.x=a.y=a.prex=a.prey=a.cost=0;
p[0][0]=a;
que.push(a);
while(!que.empty())
{
a=que.front();
que.pop();
for(i=0;i<4;i++)
{
b.x=a.x+dir[i][0];
b.y=a.y+dir[i][1];
if(!open(b.x,b.y))continue;
else
{
if(map[b.x][b.y]!='.')
j=map[b.x][b.y]-'0';
else j=0;
b.prex=a.x;b.prey=a.y;
b.cost=a.cost+1+j;
}
if(b.cost<p[b.x][b.y].cost||p[b.x][b.y].cost==-1)
{
p[b.x][b.y]=b;
que.push(b);
}
}
}
if(p[n-1][m-1].cost==-1)
{cout<<"God please help our poor hero."<<endl;
cout<<"FINISH"<<endl;
return 0;}
printpath(n-1,m-1);
}
int main()
{
int i,j;
while(cin>>n>>m)
{
memset(map,0,sizeof(map));
for(i=0;i<n;i++)
for(j=0;j<m;j++)
{
p[i][j].cost=-1;
cin>>map[i][j];
}
bfs(0,0);
}
return 0;
}