# BFS迷宫（用队列解决迷宫问题

[提交][状态][讨论版][命题人:quanxing]

## 题目描述

1 1

2 1

3 1

4 1

5 1

5 2

5 3

6 3

6 4

6 5

7 5

8 5

8 6

8 7

8 8

#include<iostream>
#include<cstring>
#include<queue>
#include<stack>
using namespace std;
int map[50][50]={
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,0,0,1,1,0,0,1},
{1,0,1,1,1,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,1},
{1,0,1,0,0,0,1,0,0,1},
{1,0,1,1,1,0,1,1,0,1},
{1,1,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
int n[4][2]={{0,-1},{1,0},{0,1},{-1,0}};
struct p{
int x,y,prex,prey;
}x[50][50];
stack<p> o;//用于调整输出格式
queue<p> que;
int dx,dy,i,v[50][50];
p k,l;
void bfs(int a,int b){
while(!que.empty()){
k=que.front();
que.pop();
for(i=0;i<4;i++){
dx=k.x+n[i][0];
dy=k.y+n[i][1];
if(dx==8&&dy==8){
v[dx][dy]=1;
x[dx][dy].x=dx;x[dx][dy].y=dy;
x[dx][dy].prex=k.x;x[dx][dy].prey=k.y;//记录前驱结点
return;//找到终点后就可以结束了
}
else if(v[dx][dy]==0&&map[dx][dy]==0){
v[dx][dy]=1;
x[dx][dy].x=dx;x[dx][dy].y=dy;
x[dx][dy].prex=k.x;x[dx][dy].prey=k.y;
que.push(x[dx][dy]);
}
}
}
}
int main(){
memset(v,0,sizeof(v));
l.x=1;l.y=1;l.prex=-1;l.prey=-1;
v[1][1]=1;
x[1][1]=l;
que.push(l);
bfs(1,1);
while(x[dx][dy].prex!=-1&&x[dx][dy].prey!=-1){
int w,e,x1,y1;
w=x[dx][dy].prex;e=x[dx][dy].prey;
o.push(x[dx][dy]);
dx=w;dy=e;
}
printf("1 1\n");
while(!o.empty()){
int x2=o.top().x;
int y2=o.top().y;
o.pop();
printf("%d %d\n",x2,y2);
}
return 0;
}