DFS走迷宫(懒猫老师C++完整版)

2024-06-21 17:38

本文主要是介绍DFS走迷宫(懒猫老师C++完整版),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

DFS走迷宫的C++完整版

  • 知识储备
    • 一:普通动态二维数组的构造
    • 二:栈的构造
    • 三:栈的逆序遍历
  • Main文件代码

该版本代码是配合 懒猫老师用DFS走迷宫视频 基于C++基础所写的完整版(实现了栈逆序遍历),适合小白系统性的学习和复习知识点,只要将下文.h和.cpp和main文件所展示的代码结合起来就是个完整的代码。

知识储备

一:普通动态二维数组的构造

  1. 二维数组中不同行的内存空间不一定连续
  2. 释放内存时,需要先释放各个元素指向的内存,最后释放指针数组名指向的内存(层层释放)
  3. 动态二维数组释放后还会有个数组名地址(指针)的字节符大小
  4. 求数组大小的函数的时候必须将数组引用传递!否则数组会退化为一个指针,无法正确的使用sizeof运算符求出数组所占内存空间大小

下面对动态创建二维数组举例

/** 动态创建 */
int **nums = new int*[10];		//申请了一个int*类型的10行空间
for(int i = 0; i < 10; i++)
{nums[i] = new int[5];		//每一行申请一个int类型的5列空间
}/** 释放空间 */
for(int i = 0; i < 10; i++)delete[] nums[i];		//原则就是层层释放
delete[] nums;

注意:静态二维数组必须是要给定行/列的,如下代码是错误示范

int M, N;
cin >> M, N;
int maze[M+2][N+2];		//这里会报错,因为这是静态数组
// M 和 N尽管你有输入,但是编译器在预编译时是看成变量的,也就是不定的二维数组

二:栈的构造

迷宫问题中构造栈,我通过创建类来实现,具体怎么构造我这就不详细说了(因为这是基本功),.h文件用来存放方法声明,.cpp文件用来实现方法
以下是.h文件的代码(我去掉了析构函数)

struct Direction	//构建结构体
{int incX, incY;
};

构建Direction结构体是为了后面构造个结构体数组,该行走方向只有上下左右,没有左上、右上之类的,所以才储存4个方向,该数组储存内容如下图,如incX = 0, incY = 1是为了向右行走(X是横向,Y是纵向)
在这里插入图片描述

struct Box	//将每个迷宫格子看成是一个结构体
{int x, y, di;//x和y分别代表迷宫格子的横纵坐标,di为当前的方向
};typedef struct Node		//这是栈节点
{Box data;struct Node* pNext;
}Node, *PNODE;class Stack
{private:PNODE pTop;PNODE pBottom;public:Stack();void initStack(Stack*);void pushStack(Stack*, Box); //将栈中的栈底元素返回并移除,用递归来实现栈逆序遍历的Box getElement(Stack&, Box&);void reverse(Stack&, Box&); void traverse(Stack*);void pop(Stack*, Box&);bool isEmpty(Stack*);
};

以下是.cpp文件代码

#include "Stack.h"
#include <iostream>
#include <stdlib.h>		//exit函数要用到
using namespace std;Stack::Stack()
{//ctor
}void Stack::initStack(Stack* pS)
{pS->pTop = new Node;if(nullptr == pS->pTop){cout << "动态内存分配失败!" << endl;exit(-1);}else{pS->pBottom = pS->pTop;pS->pTop->pNext = nullptr;}return;
}void Stack::pushStack(Stack* pS, Box temp) //temp是将一个结构体整体入栈
{PNODE pNew = new Node;pNew->data = temp;pNew->pNext = pS->pTop;pS->pTop = pNew;
}
/** 这里开始是逆序遍历栈的关键代码,等会详细讲解 */
Box Stack::getElement(Stack& s, Box& temp)
{s.pop(&s, temp);Box res = temp;if(s.isEmpty(&s)) return res;else{Box last = getElement(s, temp);s.pushStack(&s, res);return last;}
}void Stack::reverse(Stack& s, Box& temp)
{if(s.isEmpty(&s)) return;Box i  = getElement(s, temp);s.reverse(s, temp);s.pushStack(&s, i);
}
/****************************************/
void Stack::traverse(Stack* pS)
{PNODE p = pS->pTop;		//p是移动指针,在栈顶和栈底间上下移动的while(p != pS->pBottom){cout << "(" << p->data.x << ", " << p->data.y << ")" << endl;p = p->pNext;}cout << endl;return;
}void Stack::pop(Stack* pS, Box& temp)	//这里的temp一定要 采用引用
{if(isEmpty(pS)) return;else{PNODE r = pS->pTop;temp = r->data;pS->pTop = r->pNext;free(r);r = NULL;return;}
}bool Stack::isEmpty(Stack* pS)
{if(pS->pTop == pS->pBottom)return true;elsereturn false;
}

三:栈的逆序遍历

我这里提供一种递归的思路来实现,当然也可以直接在自己构建栈遍历的方法中改进。栈的逆序遍历不难实现,看图和代码自己尝试下就行。其实这个知识点,也有些题会单独拿出来考,万一你面试的时候遇上这问题呢?~

Box Stack::getElement(Stack& s, Box& temp)
{s.pop(&s, temp);	//这里的temp是引用的,会随变化而变化Box res = temp;		//这里的temp和上面的temp一样//递归结束条件:栈空的时候,返回栈最底下的单元if(s.isEmpty(&s)) return res; 	else{Box last = getElement(s, temp);		//一直递归s.pushStack(&s, res);return last;}
}

为了方便理解上面代码,请结合代码和下图来看
getElement程序步骤演示
这时我们只是把一个栈最底部的单元提出来了,那么怎么接着提取其他呢?那当然可以用递归实现,就可以成功的反转栈了(如下代码)

void Stack::reverse(Stack& s, Box& temp) //这里的temp也要用引用
{if(s.isEmpty(&s)) return;Box i  = getElement(s, temp);s.reverse(s, temp);s.pushStack(&s, i);
}

也是结合代码来看下图理解吧,这里递归的reversepushStack可能比较难理解,简单来说就是进行一次reverse就含有一个pushStack,进行两次reverse就含有两个pushStack····直到栈空,每次return(有很多次,取决于栈元素的个数)前都会执行pushStack
reverse程序结构

Main文件代码

#include <iostream>
#include "Stack.h"using namespace std;bool findPath(Stack& s, int M, int N)
{int **maze = new int*[M+2];		//动态构造二维数组for(int i = 0; i < 10; i++){maze[i] = new int[N+2];}for(int i = 0; i < M+2; i++){	//动态给定迷宫for(int j = 0; j < N+2; j++){if(i == 0 || i == M+1)maze[i][j] = 1;else if(j == 0 || j == N+1)maze[i][j] = 1;elsecin >> maze[i][j];}}Direction direct[4];		//方向数组(文章上面有图有说到)direct[0].incX = 0; direct[0].incY = 1;direct[1].incX = 1; direct[1].incY = 0;direct[2].incX = 0; direct[2].incY = -1;direct[3].incX = -1; direct[3].incY = 0;Box temp;int x, y, di;      //当前正在处理的迷宫格子int line, col;    //迷宫格子预移方向后,下一格子的行坐标、列坐标maze[1][1] = -1;temp.x = 1;temp.y = 1;temp.di = -1;		//起始点直接设置为-1代表该格子已访问过了s.pushStack(&s, temp);while(!s.isEmpty(&s)){s.pop(&s, temp);	//这里对遇到走不通的格子进行回退时起到关键作用x = temp.x; y = temp.y; di = temp.di+1;while(di < 4){  //走不通时,四个方向都尝试一遍line = x + direct[di].incX;col = y + direct[di].incY;if(maze[line][col] == 0){	//代表 预走 的格子可以走temp.x = x; temp.y = y; temp.di = di;s.pushStack(&s, temp);x = line; y = col; maze[line][col] = -1;	//标为-1是为了表明该格子已经走过,回溯时不再处理if(x == M && y == N){s.reverse(s, temp);return true;   //迷宫有路}else di = 0;}else di++;}}return false;       //迷宫无路
}int main()
{int M, N;bool res;cout << "请输入迷宫数组行数和列数:";cin >> M >> N;Stack s;s.initStack(&s);res = findPath(s, M, N);cout << boolalpha << res << endl;	//将bool转换为true/false显示cout << endl;if(res)s.traverse(&s);elsecout << "你被困在迷宫中了,等着受死吧!" << endl;return 0;
}

  ------------------以上是懒猫老师自构Stack的版本--------------------
  我们都知道C++提供了STL库,那么我们为何不用自带的stack更方便简洁呢?所以为了方便大家用C++,决定在下面开源个用STL库里stack的代码版本,同样也是实现了栈逆序遍历。

#include <bits/stdc++.h>
using namespace std;struct Direction
{int incX, incY;
};struct Box
{int x, y, di;
};Box getElement(stack<Box>& s)
{Box res = s.top();s.pop();if(s.empty()) return res;else{Box last = getElement(s);s.push(res);return last;}
}void reverseStack(stack<Box>& s)
{if(s.empty()) return;Box i = getElement(s);reverseStack(s);s.push(i);
}bool findPath(stack<Box>& s, int M, int N)
{//动态构建二维数组 new 出来的空间不一定是连续的int** maze = new int*[M+2];for(int i = 0; i < N + 2; i++)maze[i] = new int[N+2];for(int i = 0; i < M+2; i++){for(int j = 0; j < N+2; j++){if(i == 0 || i == M+1)maze[i][j] = 1;else if(j == 0 || j == N+1)maze[i][j] = 1;else cin >> maze[i][j];}}Direction direct[4];direct[0].incX = 0; direct[0].incY = 1;direct[1].incX = 1; direct[1].incY = 0;direct[2].incX = 0; direct[2].incY = -1;direct[3].incX = -1; direct[3].incY = 0;Box temp;int x, y, di;       //当前处理的单元格int row, col;     //走迷宫下一该走的单元格maze[1][1] = -1;temp.x = 1;temp.y = 1;temp.di = -1;s.push(temp);while(!s.empty()){x = s.top().x;  y = s.top().y;  di = s.top().di + 1;s.pop();while(di < 4){row = x + direct[di].incX;  col = y + direct[di].incY;if(maze[row][col] == 0){temp.x = x;  temp.y = y;  temp.di = di;s.push(temp);x = row;  y = col;  maze[row][col] = -1;if(x == M && y == N){reverseStack(s);return true;}else di = 0;}else di++;}}return false;
}void traverse(stack<Box> s)
{while(!s.empty()){Box temp = s.top();s.pop();cout << "(" << temp.x << ", " << temp.y << ")" << endl;}return;
}int main()
{int M, N;bool res;cout << "请输入迷宫数组的行数和列数:";cin >> M >> N;stack<Box> s;res = findPath(s, M, N);cout << boolalpha << res << endl;cout << endl;if(res)traverse(s);elsecout << "你被困在迷宫中了" << endl;return 0;
}

Input
8 8
0 0 1 0 0 0 1 0
0 0 1 0 0 0 1 0
0 0 0 0 1 1 0 0
0 1 1 1 0 0 0 0
0 0 0 1 0 0 0 0
0 1 0 0 0 1 0 0
0 1 1 1 0 1 1 0
1 0 0 0 0 0 0 0
  
Output
(1, 1)
(1, 2)
(2, 2)
(3, 2)
(3, 1)
(4, 1)
(5, 1)
(5, 2)
(5, 3)
(6, 3)
(6, 4)
(6, 5)
(7, 5)
(8, 5)
(8, 6)
(8, 7)
  
--------------------------------------------------------
2022年2月24号更新:
  算法竞赛的DFS走迷宫(自定义起始和结束点,打印出所有路径)

👉例题:点这里
大致题意: 第一行输入n,m代表迷宫的行数、列数,接下来输入 n 行和 m 列迷宫(1 表示可以走,0 表示不可以走),倒数第二行代表起始点,倒数第一行代表结束点。用 “→” 连接符表示方向连接

#include <bits/stdc++.h>
using namespace std;const int N = 30;int n, m;
int g[N][N], d[N][N];		//g为邻接矩阵存储图,d为记录该点是否已经走过
bool flag = false;
const int dx[4] = {0, -1, 0, 1};
const int dy[4] = {-1, 0, 1, 0};
pair<int, int> start;			//起始点
pair<int, int> over;			//结束点
pair<int, int> after[N][N];		//记录该点往后走哪个点void dfs(int xx, int yy){if(xx == over.first && yy == over.second){int a = start.first, b = start.second;flag = true;cout << "(" << a << "," << b << ")->";while(1){auto t = after[a][b];a = t.first, b = t.second;if(a == over.first && b == over.second){cout << "(" << a << "," << b << ")" << endl;break;}else cout << "(" << a << "," << b << ")->";}}int x, y;for(int i = 0; i < 4; i++){x = xx + dx[i], y = yy + dy[i];if(x >= 1 && x <= n && y >= 1 && y <= m &&d[x][y] == -1 && g[x][y] == 1){d[x][y] = 1;after[xx][yy] = {x, y};		//记录往后走哪个点dfs(x, y);d[x][y] = -1;x = xx, y = yy;}}
}int main(){cin >> n >> m;for(int i = 1; i <= n; i++)for(int j = 1; j <= m; j++)cin >> g[i][j];cin >> start.first >> start.second;cin >> over.first >> over.second;memset(d, -1, sizeof d);d[start.first][start.second] = 1;dfs(start.first, start.second);if(!flag) cout << -1 << endl;return 0;
}

路漫漫其修远兮,吾将上下而求索

这篇关于DFS走迷宫(懒猫老师C++完整版)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1081883

相关文章

C++中unordered_set哈希集合的实现

《C++中unordered_set哈希集合的实现》std::unordered_set是C++标准库中的无序关联容器,基于哈希表实现,具有元素唯一性和无序性特点,本文就来详细的介绍一下unorder... 目录一、概述二、头文件与命名空间三、常用方法与示例1. 构造与析构2. 迭代器与遍历3. 容量相关4

C++中悬垂引用(Dangling Reference) 的实现

《C++中悬垂引用(DanglingReference)的实现》C++中的悬垂引用指引用绑定的对象被销毁后引用仍存在的情况,会导致访问无效内存,下面就来详细的介绍一下产生的原因以及如何避免,感兴趣... 目录悬垂引用的产生原因1. 引用绑定到局部变量,变量超出作用域后销毁2. 引用绑定到动态分配的对象,对象

C++读写word文档(.docx)DuckX库的使用详解

《C++读写word文档(.docx)DuckX库的使用详解》DuckX是C++库,用于创建/编辑.docx文件,支持读取文档、添加段落/片段、编辑表格,解决中文乱码需更改编码方案,进阶功能含文本替换... 目录一、基本用法1. 读取文档3. 添加段落4. 添加片段3. 编辑表格二、进阶用法1. 文本替换2

C++中处理文本数据char与string的终极对比指南

《C++中处理文本数据char与string的终极对比指南》在C++编程中char和string是两种用于处理字符数据的类型,但它们在使用方式和功能上有显著的不同,:本文主要介绍C++中处理文本数... 目录1. 基本定义与本质2. 内存管理3. 操作与功能4. 性能特点5. 使用场景6. 相互转换核心区别

C++右移运算符的一个小坑及解决

《C++右移运算符的一个小坑及解决》文章指出右移运算符处理负数时左侧补1导致死循环,与除法行为不同,强调需注意补码机制以正确统计二进制1的个数... 目录我遇到了这么一个www.chinasem.cn函数由此可以看到也很好理解总结我遇到了这么一个函数template<typename T>unsigned

C++统计函数执行时间的最佳实践

《C++统计函数执行时间的最佳实践》在软件开发过程中,性能分析是优化程序的重要环节,了解函数的执行时间分布对于识别性能瓶颈至关重要,本文将分享一个C++函数执行时间统计工具,希望对大家有所帮助... 目录前言工具特性核心设计1. 数据结构设计2. 单例模式管理器3. RAII自动计时使用方法基本用法高级用法

深入解析C++ 中std::map内存管理

《深入解析C++中std::map内存管理》文章详解C++std::map内存管理,指出clear()仅删除元素可能不释放底层内存,建议用swap()与空map交换以彻底释放,针对指针类型需手动de... 目录1️、基本清空std::map2️、使用 swap 彻底释放内存3️、map 中存储指针类型的对象

C++ STL-string类底层实现过程

《C++STL-string类底层实现过程》本文实现了一个简易的string类,涵盖动态数组存储、深拷贝机制、迭代器支持、容量调整、字符串修改、运算符重载等功能,模拟标准string核心特性,重点强... 目录实现框架一、默认成员函数1.默认构造函数2.构造函数3.拷贝构造函数(重点)4.赋值运算符重载函数

C++ vector越界问题的完整解决方案

《C++vector越界问题的完整解决方案》在C++开发中,std::vector作为最常用的动态数组容器,其便捷性与性能优势使其成为处理可变长度数据的首选,然而,数组越界访问始终是威胁程序稳定性的... 目录引言一、vector越界的底层原理与危害1.1 越界访问的本质原因1.2 越界访问的实际危害二、基

c++日志库log4cplus快速入门小结

《c++日志库log4cplus快速入门小结》文章浏览阅读1.1w次,点赞9次,收藏44次。本文介绍Log4cplus,一种适用于C++的线程安全日志记录API,提供灵活的日志管理和配置控制。文章涵盖... 目录简介日志等级配置文件使用关于初始化使用示例总结参考资料简介log4j 用于Java,log4c