栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

迷宫最短路径问题(BFS、DFS)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

迷宫最短路径问题(BFS、DFS)

一、迷宫最短路径问题

   给你一个m*n的迷宫,迷宫中有障碍物(1表示障碍物),你可以上下左右移动,但不能走走过的迷宫,给出指定的起点(x,y)和指定的终点(x_l,y_l),求最短路径长度是多少,或者打印其中一个最短路径,

输入:nums={
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 0, 0,
};
输出:最短路径长度:8
最段路径为: 1 0,2 0,3 0,4 0,4 1,4 2,4 3,4 4

思路:1.使用DFS深度优先遍历来到达终点的所有路径,选择最短的路径。
    2.使用BFS层序遍历,一层一层往外扩张,使用结构体简化操作

DFS
//***************************上下左右迷宫,有障碍物,DFS************************
 vector dx = { -1,1,0,0 };
 vector dy = { 0,0,-1,1 };
 vector> path;
 vector> res;
 void dfs(vector> nums,int x,int y,int x_l,int y_l) {
	 if (x == x_l && y == y_l) {                                   
		if (res.size() == 0 || res.size() > path.size()) res = path;  //更新最短路径
		 return;
	 }
	 for (int i = 0; i < 4; i++) {                                    //上下左右
		 int x_currt = x + dx[i];
		 int y_currt = y + dy[i];
		 if (x_currt < 0 || x_currt >= nums.size() || y_currt < 0 || y_currt>=nums[0].size()  //边界条件,障碍物,已经走过
			 || nums[x_currt][y_currt] == -1 || nums[x_currt][y_currt] == 1) continue;
		 nums[x_currt][y_currt] = -1;
		 path.push_back({ x_currt ,y_currt });
		 dfs(nums, x_currt, y_currt, x_l, y_l);       
		 path.pop_back();
	 }
 }
BFS
//***************************上下左右迷宫,有障碍物,BFS**********************
//使用队列辅助,每层出栈时,把下层的压栈。
 class P {
 public:
	 int x;  //横坐标
	 int y;  //纵坐标
	 int len; //路径长度
	 vector> path; //记录路径
 };
 void bfs(vector> nums, int x, int y, int x_l, int y_l) {
	   queue

que; //用队列记录每个结构体在每层的路径和路径长度,这样同一层的点的路径长度是相同的。 vector> path; P currt; currt.x = x; currt.y = y; currt.len = 0; currt.path = path; que.push(currt); //入队 while (!que.empty()) { currt = que.front(); //弹出队首结点 que.pop(); if (currt.x == x_l && currt.y == y_l) { //如果这一层是终点则退出遍历 cout << "最短路径长度:"< //上下左右 int x_currt = currt.x + dx[i]; int y_currt = currt.y + dy[i]; if (x_currt < 0 || x_currt >= nums.size() || y_currt < 0 || y_currt >= nums[0].size() //判断边界条件和障碍以及走过 || nums[x_currt][y_currt] == -1 || nums[x_currt][y_currt] == 1) continue; P next; next.x = x_currt; next.y = y_currt; next.len = currt.len + 1; next.path = currt.path; next.path.push_back({ x_currt ,y_currt}); que.push(next); //把下一层的点压入队列 nums[x_currt][y_currt] = -1; //标记走过的路 } } return ; }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/948003.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号