其他分享
首页 > 其他分享> > bfs求最短路并打印出路径

bfs求最短路并打印出路径

作者:互联网

义一个二维数组: 

int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)


//#include<bits/stdc++.h>
#include<iostream>
#include<cstring>
#include<queue>
#include<stack>
#include<cstdio>
using namespace std;
struct Point
{
int x,y,step;
Point(){}
Point(int xx,int yy,int s)
{
x=xx;
y=yy;
step=s;
}
};
Point PP[30];
int x[]={-1,0,1,0};
int y[]={0,1,0,-1};
int a[5][5],b[5][5];     //b中存了bfs最短树,要正确写出最短树必须在bfs时去重,就是把走过的a中的值变为-1加以区分
int ans=0;
void bfs()
{
queue<Point>p;
Point u(0,0,0);
p.push(u);
a[0][0]=-1;
while (!p.empty())
{
Point uu=p.front();
p.pop();
if (uu.x==4&&uu.y==4){
ans=uu.step;
return;
}
for (int i=0;i<4;i++)
{
int xx=uu.x+x[i];
int yy=uu.y+y[i];
if (xx>=0&&xx<=4&&yy>=0&&yy<=4&&a[xx][yy]==0)
{
a[xx][yy]=-1;
Point pp(xx,yy,uu.step+1);
b[xx][yy]=uu.step+1;
p.push(pp);
}
}

}
}
int main()
{
int n=5;
memset(b,0,sizeof(b));
for (int i=0;i<5;i++)
{
for (int j=0;j<5;j++)
{
cin>>a[i][j];
}
}
bfs();
for (int i=0;i<=4;i++)
{
for (int j=0;j<=4;j++)
{
cout<<b[i][j];
}
cout<<endl;
}
// cout<<b[4][4]<<endl;
stack<Point>res;
res.push(Point(4,4,ans));
ans--;
while (ans>0)
{
Point pp=res.top();
for (int i=0;i<4;i++)
{
int xx=pp.x+x[i];
int yy=pp.y+y[i];
if (xx>=0&&xx<=4&&yy>=0&&yy<=4&&b[xx][yy]==ans)
{
res.push(Point(xx,yy,ans));
ans--;
}
}
}
cout<<"(0, 0)"<<endl;
while (!res.empty())
{
Point pp=res.top();
res.pop();
printf("(%d, %d)\n",pp.x,pp.y);
}
return 0;
}

标签:并打印,yy,pp,Point,int,短路,bfs,uu,xx
来源: https://www.cnblogs.com/wantchange/p/11243562.html