BFS专题4 迷宫最短路径(输出路径)

BFS算法解决迷宫路径问题
本文介绍了使用广度优先搜索(BFS)方法在给定迷宫地图中寻找从起点到终点的路径,通过记录每个点的前一个最优位置实现路径追踪。

题目:样例:

输入
3 3
0 1 0
0 0 0
0 1 0

输出
1 1
2 1
2 2
2 3
3 3

思路:

        这里刚开始看的时候会可能有点复杂了,因为是递归。

但是只要理解了含义,脑袋里模拟一下还是可以理解的。首先还是 之前那样 BFS 常规搜索

只是这里不用输出步数了,所以我们可以省略一层循环,直接搜索求路径。

求路径的方法核心思想就是 记录每个点是由哪上一个点所得来的。

然后记录完全部的点所对应的上一个点后,从终点递归一遍到起点,然后输出路径即可。

代码详解如下:

#include <iostream>
#include <queue>
#include <cstring>
#define endl '\n'
#define x first
#define y second
#define mk make_pair
#pragma GCC optimize(3,"Ofast","inline")
#define ___G std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
using namespace std;
const int N = 300;

using PII = pair<int, int>;

// 控制走动方向
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

int n, m;	// 迷宫大小
int r[N][N];	// 记录走动过的地方
int g[N][N];	// 迷宫地图

PII pre[N][N];	// 记录路径

// 走动下一个坐标条件
inline bool isRun(int x, int y)
{
	return (x >= 0 && x < n && y >= 0 && y < m && !r[x][y] && !g[x][y]);
}


inline bool BFS(int x, int y)
{
	// 存储坐标
	queue<PII>q;
	// 存储起点
	q.push(mk(x, y));

	// 开始广度搜索
	while (q.size())
	{
		auto now = q.front();
		q.pop();

		if (now.x == n - 1 && now.y == m - 1)
		{
			// 如果已经走动到了右下角的出口
			// 结束搜索
			return false;
		}

		// 标记已经走动过了当前的地点
		r[now.x][now.y] = true;

		// 枚举四个方向能否走动
		for (int i = 0; i < 4; ++i)
		{
			// 取出该方向的坐标
			int bx = now.x + dx[i];
			int by = now.y + dy[i];

			// 判断是否满足走动条件
			if (isRun(bx, by))
			{
				// 存储下一次走动的坐标
				q.push(mk(bx, by));

				// 标记下一次会走动的坐标
				r[bx][by] = true;

				// 记录路径
				// 下一个点是 由 哪上一个最优的点得到的
				// 然后 反过来递归回去找 就得到 起点到终点的路径了
				pre[bx][by] = mk(now.x, now.y);
			}
		}
	}
	// 如果不能走到终点输出结果
	return true;
}

inline void Print_path(PII now)
{
	// 取出当前 now 对应的上一个的坐标
	auto previous = pre[now.x][now.y];

	// 如果递归到达了边界,说明已经到达了起点
	// 开始输出路径
	if (previous == PII(-1, -1))
	{
		cout << now.x + 1 << ' ' << now.y + 1 << endl;
		return ;
	}

	// 继续递归往回找路径
	Print_path(previous);

	cout << now.x + 1 << ' ' << now.y + 1 << endl;
	return ;
}
inline void solve()
{
	// 这里是初始化路径全部为 -1,-1,作为递归边界
	memset(pre, -1, sizeof pre);

	cin >> n >> m;
	for (int i = 0; i < n; ++i)
	{
		for (int j = 0; j < m; ++j)
		{
			cin >> g[i][j];
		}
	}
	if (BFS(0, 0))
	{
		puts("-1");
	}
	else
	{
		// 打印路径
		// 由于是从后面开始记录上一个路径点
		// 所以我们应该从终点开始递归查找路径
		Print_path(mk(n - 1, m - 1));
	}
}


int main()
{
//	freopen("a.txt", "r", stdin);
	___G;
	int _t = 1;
//	cin >> _t;
	while (_t--)
	{
		solve();
	}

	return 0;
}

最后提交:

### 广度优先搜索(BFS)算法实现 广度优先搜索(BFS)是一种用于遍历或搜索树或图的算法。它按照层次顺序访问节点,通常从根节点开始,逐层向下扩展到叶子节点[^3]。 以下是基于队列的数据结构来实现 BFS 的标准方法: #### 使用伪代码描述 BFS 实现 ```plaintext function BFS(graph, start_vertex): create an empty queue Q enqueue(start_vertex) into Q mark start_vertex as visited while Q is not empty: current_vertex = dequeue(Q) visit(current_vertex) for each neighbor of current_vertex in graph.adjacentEdges(current_vertex): if neighbor is not visited: mark neighbor as visited enqueue(neighbor) into Q ``` #### 基于 Python 的 BFS 实现 下面是一个完整的 Python 实现示例,适用于无向图或有向图中的 BFS 遍历: ```python from collections import deque def bfs(graph, start_node): """ Perform Breadth-First Search (BFS) on a given graph. :param graph: Dictionary representing adjacency list of the graph :param start_node: Starting node for BFS traversal :return: List containing nodes visited during BFS traversal """ visited = set() # Set to keep track of visited nodes result = [] # List to store the order of visited nodes queue = deque([start_node]) # Initialize queue with the start node visited.add(start_node) # Mark the start node as visited while queue: current_node = queue.popleft() result.append(current_node) # Add current node to the result list # Explore neighbors of the current node for neighbor in graph.get(current_node, []): if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) return result # Example usage if __name__ == "__main__": # Define a sample graph using an adjacency dictionary graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': [] } start_node = 'A' traversal_order = bfs(graph, start_node) print(f"BFS Traversal Order: {traversal_order}") ``` 此代码实现了 BFS 算法的核心逻辑,并通过 `deque` 数据结构模拟了一个先进先出(FIFO)队列的行为。对于给定的输入图,该函数返回按 BFS 访问顺序排列的节点列表[^4]。 #### 关键特性说明 1. **时间复杂度**: 如果图中有 \(V\) 个顶点和 \(E\) 条边,则 BFS 的时间复杂度为 \(O(V + E)\)[^1]。 2. **空间复杂度**: 主要由队列占用的空间决定,在最坏情况下可能达到 \(O(V)\),即当所有顶点都在同一层时[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值