迷宫问题(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)

主要涉及的算法是基础的bfs算法,考点在于路径的记录以及输出,可以选择使用一个结构体数组来记录每一个格子的上一步坐标,再输出时进行递归操作即可得到结果

#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
struct pos {
	int x;
	int y;
};
int room[10][10];
pos f[10][10];
int dir_x[4] = { 0,1,0,-1 };
int dir_y[4] = { -1,0,1,0 };
void print(int x, int y)
{
	if (x == 1 && y == 1)
	{
		cout << "(0, 0)" << endl;
		return;
	}
	print(f[x][y].x, f[x][y].y);
	cout << "(" << x - 1 << ", " << y - 1 << ")" << endl;
}
void bfs(int x, int y)
{
	queue<pos> q;
	int cnt = 2;
	q.push({ x,y });
	while (!q.empty())
	{
		pos start = q.front();
		q.pop();
		room[start.x][start.y] = cnt++;
		for (int i = 0; i < 4; i++)
		{
			int a = start.x + dir_x[i];
			int b = start.y + dir_y[i];
			if (room[a][b] == 0)
			{
				f[a][b] = start;
				q.push({ a,b });
			}
		}
	}
}
int main()
{
	memset(room, 1, sizeof(room));
	for (int i = 1; i <= 5; i++)
		for (int j = 1; j <= 5; j++)
			cin >> room[i][j];
	bfs(1, 1);
	print(5, 5);
	return 0;
}
迷宫问题通常涉及到路径寻找算法,其中一种常见的非递归解决方案是使用广度优先搜索(BFS),也称为宽度优先搜索。以下是使用C++实现迷宫问题的一种非递归版本: ```cpp #include <iostream> #include <queue> #include <vector> // 定义迷宫的结构 struct Cell { bool visited; // 是否访问过 bool is_wall; // 走廊还是墙壁 }; // 使用邻接矩阵表示迷宫 const int ROWS = N; // 迷宫行数 const int COLS = M; // 迷宫列数 std::vector<std::vector<Cell>> maze(ROWS, std::vector<Cell>(COLS)); // 初始化起点 (0, 0) 和终点 (ROWS - 1, COLS - 1) Cell start = {false, false}; Cell end = {false, false}; bool is_valid(int row, int col) { return row >= 0 && row < ROWS && col >= 0 && col < COLS && !maze[row][col].is_wall; } void bfs(int start_row, int start_col) { std::queue<pair<int, int>> q; maze[start_row][start_col].visited = true; q.push({start_row, start_col}); while (!q.empty()) { auto [row, col] = q.front(); q.pop(); if (row == end.row && col == end.col) { std::cout << "找到了从起点到终点的路径!" << std::endl; break; } for (int dr = -1; dr <= 1; ++dr) { for (int dc = -1; dc <= 1; ++dc) { int new_row = row + dr; int new_col = col + dc; if (is_valid(new_row, new_col)) { maze[new_row][new_col].visited = true; q.push({new_row, new_col}); } } } } } int main() { // 初始化迷宫和起点、终点位置... bfs(start.row, start.col); return 0; } ``` 在这个例子中,我们首先定义了一个`Cell`结构体用于存储每个网格的位置及其状态。然后,使用一个队列(`std::queue`)来进行BFS,每次从当前节点出发,探索其相邻未访问过的节点,直到找到终点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值