迷宫问题 (BFS)

定义一个二维数组:

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)
关键是移动轨迹的保存。还是看了别的大佬的方法写的
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int maze[5][5];
int vis[5][5];
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};
//int dis[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
struct node
	{
		int x,y;
		int step;
		int num[50];
		friend bool operator < (node a,node b)
		{
			return a.step > b.step;
		}
	}e1,e2;
node BFS()
{
	memset(vis,0,sizeof(vis));
	priority_queue<node> que;
	//queue<node> que;
	e1.x = 0,e1.y = 0,e1.step = 0;
	que.push(e1);
	vis[0][0] = 1; 
	while (!que.empty())
	{
		e1 = que.top();
		//e1 = que.front();
		que.pop();
		if (e1.x==4 && e1.y==4)
			return e1;
		for (int i=0;i<4;i++)
		{
			e2 = e1;
			e2.x = e1.x + dx[i];
			e2.y = e1.y + dy[i];
			if (0<=e2.x && e2.x<5 && 0<=e2.y && e2.y<5 && maze[e2.x][e2.y]!=1 && vis[e2.x][e2.y]!=1)
			{
				e2.step = e1.step + 1;
				e2.num[e1.step] = i;
				que.push(e2);
				vis[e2.x][e2.y] = 1;
			}
		}
	}
	return e1;
}
int x = 0,y = 0;
void print(node w)
{
	int i;
	for (i=0;i<=w.step;i++)
	{
		printf("(%d, %d)\n",x,y);
		if (i!=w.step)
		{
			//x = dx[w.num[i]];
			//y = dy[w.num[i]];
			x+=dx[w.num[i]];
                        y+=dy[w.num[i]];
		}
	}
}
int main()
{
	int i,j;
	for (i=0;i<5;i++)
		for (j=0;j<5;j++)
			scanf("%d",&maze[i][j]);
	node ans = BFS();
	print(ans);
	return 0;
}

 

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