在算出最短的路径的基础上,在结构体中定义额外的string来记录每一步走的路径,并保留在队列中以此来实现记录路径的功能。
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int a[100][100]={0};
int v[100][100]={0};
int flag=0;
struct point
{
int x;
int y;
int step;
string s;
};
queue<point> r;
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
string s[4]={"上","下","左","右"};
int main()
{
int m,n;
cin >> m >> n ;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin >> a[i][j] ;
}
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
v[i][j]=1 ;
}
}
int xStart,yStart;
cin >> xStart >> yStart ;
int xEnd,yEnd;
cin >> xEnd >> yEnd ;
xStart--;
yStart--;
xEnd--;
yEnd--;
point start;
start.x=xStart;
start.y=yStart;
start.step=0;
v[xStart][yStart]=2;
r.push(start);
while(!r.empty())
{
int x=r.front().x;
int y=r.front().y;
if(x==xEnd && y==yEnd)
{
flag=1;
cout << "最短步骤" << r.front().step << endl ;
cout << r.front().s << endl ;
break;
}
for(int k=0;k<3;k++)
{
int tx,ty;
tx=x+dx[k];
ty=y+dy[k];
if(a[tx][ty]==1 && v[tx][ty]==1)
{
point temp;
temp.x=tx;
temp.y=ty;
if(k==0)
{
temp.s=r.front().s+"上";
}
if(k==1)
{
temp.s=r.front().s+"右";
}
if(k==2)
{
temp.s=r.front().s+"下";
}
if(k==3)
{
temp.s=r.front().s+"左";
}
v[tx][ty]=2;
temp.step=r.front().step+1;
r.push(temp);
}
}
r.pop();
}
if(flag==0)
{
cout << "no answer!" << endl;
}
return 0;
}