C++ queue应用之电路布线(迷宫的最短路径)

本文介绍了一种使用C++和Queue解决迷宫最短路径问题的方法。在给定的4领域可达的迷宫中,通过Queue进行路径搜索,并利用Stack进行结果倒序输出,以找到起点到终点的最短路径。
摘要由CSDN通过智能技术生成

假如我们给定一个如下所示的迷宫,蓝色表示边界或不可通过的区域(用1表示),白色表示可以通过的区域(用0表示),绿色表示起始点,红色表示到达的终点。这样可以用一个数组表示这个Maze。

我们要做的是找到从起始点到终点的最短路径。要求用4领域可通过。

下面是我用 Queue 实现的寻径算法:

#include "stdafx.h"
#include <iostream>
#include "Queue.h"
#include <stack>
#include <iomanip>
using namespace std;

class Position
{
public:
	Position(int x=0,int y=0):row(x),col(y){}
	int row;
	int col;
};

const int m=7;
const int n=8;
int Maze[m+2][n+2] = {    1,1,1,1,1,1,1,1,1,1,
	                                       1,0,0,0,0,0,1,0,0,1,
	                                       1,0,1,1,1,0,0,1,0,1,
	                                       1,0,0,1,0,1,0,0,0,1,
	                                       1,1,0,1,0,1,1,0,1,1,
	                        
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
迷宫最短路径问题可以通过广度优先搜索(BFS)算法来解决。下面是C++语言实现迷宫最短路径问题的示例代码: ```c++ #include <iostream> #include <queue> #include <vector> using namespace std; const int MAXN = 100; const int INF = 0x3f3f3f3f; struct Node { int x, y, step; }; int maze[MAXN][MAXN]; // 迷宫图 int dis[MAXN][MAXN]; // 记录到每个点的最短距离 int n, m; // 迷宫大小 // BFS搜索 void bfs(int sx, int sy) { queue<Node> q; q.push({sx, sy, 0}); dis[sx][sy] = 0; while (!q.empty()) { Node cur = q.front(); q.pop(); int x = cur.x, y = cur.y, step = cur.step; if (x == n && y == m) { // 已到达终点,结束搜索 break; } // 向上下左右四个方向扩展 if (x - 1 >= 1 && maze[x - 1][y] == 0 && dis[x - 1][y] == INF) { dis[x - 1][y] = step + 1; q.push({x - 1, y, step + 1}); } if (x + 1 <= n && maze[x + 1][y] == 0 && dis[x + 1][y] == INF) { dis[x + 1][y] = step + 1; q.push({x + 1, y, step + 1}); } if (y - 1 >= 1 && maze[x][y - 1] == 0 && dis[x][y - 1] == INF) { dis[x][y - 1] = step + 1; q.push({x, y - 1, step + 1}); } if (y + 1 <= m && maze[x][y + 1] == 0 && dis[x][y + 1] == INF) { dis[x][y + 1] = step + 1; q.push({x, y + 1, step + 1}); } } } int main() { cin >> n >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> maze[i][j]; dis[i][j] = INF; } } bfs(1, 1); // 从起点开始搜索 cout << dis[n][m] << endl; // 输出到终点的最短距离 return 0; } ``` 在这个示例代码中,`maze`数组表示迷宫图,0表示可以通行的路,1表示障碍物。`dis`数组表示到每个点的最短距离,`INF`表示该点未被访问过。`bfs`函数使用BFS算法搜索迷宫最短路径。在主函数中,首先输入迷宫大小和迷宫图,然后调用`bfs`函数从起点开始搜索,最后输出到终点的最短距离。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值