走迷宫1(广度优先)

1、走迷宫广度优先算法原理
对于图的遍历有主要有两种比较经典的算法,广度和深度优先遍历,广度优先遍历的关键在与构建
遍历图的一队列。具体的广度的原理,一般算法分析的书籍上面都有详细的说明,简单的来说就是,广度
优先就是先对图中一个点的周围的相邻的点都处理完了之后,在依次处理周边的点,所以对图的广度搜索
用队列存储就够比较方便。深度自然用栈比较好。深度的遍历的代码在其他的两篇博客中:
2、具体的代码
代码是对一个5*6的图进行的遍历,图中1代表障碍,0代表通路,入口(0,1)->出口(3,5)。
从图中可以看到一共有两条路径,我们找出的是最优的路径,即最短的路径。
1 0 1 1 1 1
1 0 1 0 0 0
1 0 0 0 1 0
1 1 0 0 0 0
1 1 1 0 1 1

/*+++++++++++++++++++++++++++++++
+ 走迷宫(C版)
+
+ 广度优先遍历算法,找出最优路劲。
+author:zhouyongxyz2013-4-13 21:50
++++++++++++++++++++++++++++++++++++++++++*/
#include <cstdio>

#define M 5
#define N 6
struct node
{
int x,y;
int fa;
node(){x=y=fa=0;};
}q[M*N];
int vis[M][N];
static int dx[]={-1,1,0,0};
static int dy[]={0,0,-1,1};

void print_ans(int idx);
int main()
{
int a[M][N]={
{1,0,1,1,1,1},
{1,0,1,0,0,0},
{1,0,0,0,1,0},
{1,1,1,0,0,0},
{1,1,1,0,1,1}
};
int front=0,rear;
q[front].x=0;
q[front].y=1;
rear=1;
while(front<rear)
{
node& u=q[front];
if(u.x==3&&u.y==5)
{
print_ans(front);
break;
}
for(int i=0;i<4;i++)
{
int newx=u.x+dx[i],newy=u.y+dy[i];
if(newx>=0&&newx<M&&newy>=0&&newy<N&&!vis[newx][newy]&&a[newx][newy]==0)
{
node& v=q[rear];
v.x=newx;
v.y=newy;
v.fa=front;
rear++;
}
}
front++;
}
return 0;
}
void print_ans(int idx)
{
if(q[idx].fa!=idx)
print_ans(q[idx].fa);
printf("(%d,%d)->",q[idx].x,q[idx].y);
}


发布了35 篇原创文章 · 获赞 9 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/ZHOUYONGXYZ/article/details/8798915
今日推荐