Given Map 5 * 5, 1 wall, 0 for space, walked the lower left corner from the top left corner
Is to go all the paths are recorded, but the
search recursive and non-recursive form
This code uses a non-recursive form
bfs + recording path
For num [i] .pre = head his understanding there are many routes, each point is a point came from, but there is always a path to reach the terminal is, therefore, just we need to get to a head end you can follow the path marked back
#include <iostream>
#include <cstdio>
using namespace std;
char a[10][10];
int dir[4][2]={1,0,-1,0,0,1,0,-1};
struct node{
int x,y;
int pre;
}num[1200];
void print(int n){//输出路径,当xx与yy到达终点的时候,就把head传入,
if(num[n].pre != -1){
print(num[n].pre);
printf("(%d, %d)\n",num[n].x,num[n].y);
}
}
void bfs(){
int head=0;
int rear=0;
num[rear].x=0,num[rear].y=0,num[rear++].pre=-1;//初始路径记录
while(head<rear){
for(int i=0;i<4;i++){
int xx=num[head].x+dir[i][0];
int yy=num[head].y+dir[i][1];
if(xx>=5||xx<0||yy>=5||yy<0||a[xx][yy]==1)continue;
a[xx][yy]=1;//标记走过了
num[rear].x=xx;
num[rear].y=yy;
num[rear].pre=head;
rear++;//rear的值一只增加,只要一个点的4个方向存在空地
if(xx==4&&yy==4)print(head);
}
head++;
}
}
int main(){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
scanf("%d",&a[i][j]);
}
}
printf("(0, 0)\n");
bfs();
printf("(4, 4)\n");
return 0;
}