C++广度优先搜索算法之迷宫问题

迷宫问题

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)

其实这道题,只是在迷宫求最短路径上加上了输出路径,取消了输出最少次数,所以只要让wayx、wayy和pre数组同步就行了。

就像这样:

#include<cstdio>
#include<cstring>
int head=0,tail=1,nextx,nexty;
int pre[100000],a[100000],b[100000];
int x[4]={0,0,1,-1},y[4]={1,-1,0,0};
bool mark[5][5];
int map[5][5];
int wayx[25],wayy[25];
void find(int d)
{
    if(pre[d]!=0){find(pre[d]);printf("(%d, %d)\n",wayx[d],wayy[d]);}
}
bool check(int x,int y)
{
    if(x<5&&y<5&&x>=0&&y>=0)return 1;
    return 0;
}
void bfs()
{
    a[1]=0;
    b[1]=0;
    mark[0][0]=1;
    pre[1]=0;
    head=0;tail=1;
    while(head!=tail)
	{
		head++;
		for(int i=0;i<4;i++)
		{
			nextx=a[head]+x[i];
			nexty=b[head]+y[i]; 
			if(check(nextx,nexty)&&!mark[nextx][nexty]&&map[nextx][nexty]==0)
			{
				tail++;
				a[tail]=nextx;
                b[tail]=nexty;
				pre[tail]=head;
				wayx[tail]=nextx;
				wayy[tail]=nexty;
				mark[nextx][nexty]=1; 
				if(a[tail]==4&&b[tail]==4)
				{
					printf("(0, 0)\n");
					find(tail);
					return ;
				}
			}
		}
	}
}
main()
{
	for(int i=0;i<5;i++)
		for(int j=0;j<5;j++)
			scanf("%d",&map[i][j]);
	bfs();
}

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/c20190413/article/details/73103529
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞