定义一个二维数组:
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)
这里就是自己模拟一个队列,结构体里设置一个pre记录他前一个节点,打印的时候就递归进去,先打印最开始的节点
#include<iostream>
using namespace std;
int mp[6][6];
int vis[6][6];
int mov[5][2]={{1,0},{-1,0},{0,1},{0,-1}};
int end=0,front=1;
struct node{
int x;
int y;
int pre;
}q[55],now;
void print(int end){//打印
while(q[end].pre !=-1){
print(q[end].pre );//递归进去,先打印他的上一个节点
printf("(%d, %d)\n",q[end].x ,q[end].y );
return ;
}
printf("(0, 0)\n");
}
void bfs(){
while(end<front){
if(q[end].x ==4&&q[end].y ==4){//到达终点
print(end);
return ;
}
for(int i=0;i<4;i++){//四个方向
now.x =q[end].x +mov[i][0];
now.y =q[end].y +mov[i][1];
now.pre =end;//记录上一个节点
if(now.x <0||now.x >4||now.y <0||now.y >4)
continue;
if(vis[now.x ][now.y ]||mp[now.x ][now.y ])
continue;
vis[now.x ][now.y ]=1;
q[front]=now;//入队
front++;
}
end++;
}
}
int main(){
for(int i=0;i<5;i++){//输入数据
for(int j=0;j<5;j++){
scanf("%d",&mp[i][j]);
}
}
q[0].x =0;
q[0].y =0;
q[0].pre =-1;
bfs();
return 0;
}
再加上一个跟别的大佬学的打印路径的绝佳做法
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<vector>
#include<cmath>
const int maxn=1e5+5;
typedef long long ll;
using namespace std;
int n=5;
struct node{
int x;
int y;
};
int mp[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,
};
int vis[5][5];
queue<node> q;
int mov[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
void bfs(){
vis[4][4]=0;
struct node temp;
temp.x =4;
temp.y =4;
q.push(temp);
while(!q.empty() ){
struct node now = q.front() ;
q.pop() ;
for(int i=0;i<4;i++){
struct node tmp;
int fx=tmp.x =now.x +mov[i][0];
int fy=tmp.y =now.y +mov[i][1];
if(fx<0||fy<0||fx>=n||fy>=n)
continue;
if(mp[fx][fy]==0&&vis[fx][fy]==-1){
vis[fx][fy]=vis[now.x ][now.y ]+1;
q.push(tmp);
}
}
}
}
int main(){
memset(vis,-1,sizeof(vis));
bfs();
int x=0;
int y=0;
cout<<"(0, 0)"<<endl;
while(x!=4||y!=4){
for(int i=0;i<4;i++){
int fx=x+mov[i][0];
int fy=y+mov[i][1];
if(vis[fx][fy]+1==vis[x][y]&&mp[fx][fy]==0){
x=fx;
y=fy;
cout<<"("<<x<<", "<<y<<")"<<endl;
}
}
}
return 0;
}