您的位置:首页 > 其它

BFS经典例题—迷宫问题

2016-04-05 19:21 369 查看
Description

定义一个二维数组: 
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)


————————————————————————————————————————————————

迷宫问题困扰了我很久很久,最后还是靠别人的帮忙,明白了思路,才最终写了出来。这个迷宫问题不是难在BFS寻找最短步数中,而是难在怎么去记录他的正确走法的坐标,我尝试了好几种方法都无效。

最后,我明白了正确的方法,要多开一个5*5的数组,来记录每一个坐标上一步是什么。这里可以记录上一步到这里的方向向量,也可以直接记录上一步的坐标。当BFS寻找到右下角的点的时候,从最后一个点开始向上通过这个数组往回推,得到一系列坐标,可以存放在栈中,也可以直接放在一个数组中,最后输出这些坐标就可以了。

代码:

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=6;
bool vst[maxn][maxn]; // 访问标记
int dir[4][2]={0,1,0,-1,1,0,-1,0}; // 方向向量 右,左,上,下
int migong[maxn][maxn];
int fang[maxn][maxn];//记录上一步的方向向量

struct State // BFS 队列中的状态数据结构
{
int x,y; // 坐标位置
int Step_Counter; // 搜索步数统计器
};

State t,a[30];

bool CheckState(State s) // 约束条件检验
{
if(!vst[s.x][s.y] && s.x>=0 && s.x<5 && s.y>=0 && s.y<5) // 满足条件
return 1;
else // 约束条件冲突
return 0;
}

void bfs(State st)
{
queue <State> q; // BFS 队列
State now,next; // 定义2 个状态,当前和下一个
st.Step_Counter=0; // 计数器清零
q.push(st); // 入队
vst[st.x][st.y]=1; // 访问标记
int k=0,i,j;
while(!q.empty())
{
now=q.front(); // 取队首元素进行扩展
if(now.x==4 && now.y==4) // 出现目标态,此时为Step_Counter 的最小值,可以退出即可
{
printf("%d\n",now.Step_Counter); // 做相关处理
a[k++]=now;
next=now;
while(1)
{
switch(fang[now.x][now.y])
{
case 0:
next.y=now.y-1;
break;
case 1:
next.y=now.y+1;
break;
case 2:
next.x=now.x-1;
break;
case 3:
next.x=now.x+1;
}
a[k++]=next;
now=next;
if(next.x==0&&next.y==0)
break;
}
k--;
while(k>=0)
{
printf("(%d, %d)\n",a[k].x,a[k].y);
k--;
}
return;
}
for(int i=0;i<4;i++)
{
next.x=now.x+dir[i][0]; // 按照规则生成 下一个状态
next.y=now.y+dir[i][1];
next.Step_Counter=now.Step_Counter+1; // 计数器加1
if(CheckState(next)) // 如果状态满足约束条件则入队
{
fang[next.x][next.y]=i;
q.push(next);
vst[next.x][next.y]=1; //访问标记
}
}
q.pop(); // 队首元素出队
}
return;
}

int main()
{
int i,j;
for(i=0;i<5;i++)
for(j=0;j<5;j++)
{
scanf("%d",&migong[i][j]);
if(migong[i][j]==1)
{
vst[i][j]=true;
}
}
t.x=0;
t.y=0;
bfs(t);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: