bfs,用数组来构建队列,用front指针来连接每一步
输出的时候注意(0, 0)逗号后又一个空格。。。。被坑了一次
#include <iostream>
using namespace std;
struct step{
int x,y;
step *front;
void init(int xx,int yy){
x=xx;
y=yy;
}
};
int dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}};
int sq[5][5];
step q[30];
step bfs(){
int i,nx,ny,x,y;
step start;
start.init(4,4);
start.front=NULL;
q[0]=start;
int j=0,l=1;
while(j<=l){
x=q[j].x;
y=q[j].y;
for(i=0;i<4;i++){
nx=x+dir[i][0];
ny=y+dir[i][1];
if(nx<0||nx>4||ny<0||ny>4)continue;
if(sq[ny][nx]==1)continue;
sq[ny][nx]=1;
step s;
s.init(nx,ny);
s.front=&q[j];
if(s.x==0&&s.y==0)return s;
q[l]=s;
l++;
}
j++;
}
return start;
}
int main(){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
cin>>sq[i][j];
}
}
step *s;
step b;
b=bfs();
s=&b;
while(s->front!=NULL){
cout<<"("<<s->y<<", "<<s->x<<")"<<endl;
s=s->front;
}
cout<<"(4, 4)"<<endl;
return 0;
}
原文地址:http://www.cnblogs.com/Mr-Xu-JH/p/3855016.html