当前位置:网站首页>DFS和BFS概念及实践+acwing 842 排列数字(dfs) +acwing 844. 走迷宫(bfs)
DFS和BFS概念及实践+acwing 842 排列数字(dfs) +acwing 844. 走迷宫(bfs)
2022-07-06 22:04:00 【_刘小雨】
DFS (深搜), 也有说就是递归的
执着: 一直搜到底,然后回溯下一个节点
数据结构 : stack, 空间:O(h) h: 是高度
不具有最短路性质(思路比较奇怪的,对空间要求比较高的)
重要概念: 回溯,剪枝
BFS (宽搜)
稳重:一层一层搜索
数据结构 : queue, 空间:O(2h) h: 是高度
具有最短路性质(当每条路权重是1)
DFS 例题讲解:可以用来理解递归的思想
acwing 842 排列数字
给定一个整数 n,将数字 1∼n 排成一排,将会有很多种排列方法。
现在,请你按照字典序将所有的排列方法输出。
输入格式
共一行,包含一个整数 n。
输出格式
按字典序输出所有排列方案,每个方案占一行。
数据范围
1≤n≤7
输入样例:
3
输出样例:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
思想:
对于全排列问题,可以画出下面的搜索树
递归函数调用全过程
code:
// 回溯的时候是系统中自动分配的栈回调。
#include <iostream>
using namespace std;
const int N = 10;
int n;
int path[N];
bool st[N]; // 保存之前的点是否遍历 == true 表示已经过了
void dfs(int u)
{
if(u == n)
{
// 说明所有的位置填满, 这里从0开始,在main函数中,对应的从0开始
for(int i=0; i<n; i++) cout << path[i] << ' ';
cout << endl;
return;
}
// 这里是确定哪几个点可以被选择
for(int i=1; i<=n; i++) // 这里需要找哪些点没有被枚举
{
if(!st[i])
{
path[u] = i;
st[i] = true;
dfs(u+ 1);
// 恢复现场
st[i] = false;
//path[u] = 0; // 可以删掉, 因为这里的值被覆盖掉
}
}
}
int main()
{
cin >> n;
dfs(0); // 从第0个位置开始看
return 0;
}
讲解上述代码流程:
BFS: 为什么能搜到最短路呢
它是一层一层搜索的,只有当图中权重是一样的,这样搜才是最短路的
DFS 一般没有常用的框架, 但是BFS 宽搜 有常用的框架, 所以看下面
常用的解法步骤:
- 初始状态放入队列
- 放入while, 不空
- 在while 中 每次拿到队头
- 扩展 队头
- 结束
伪代码:
queue <- 初始状态
while queue 不空
{
t <- 队头
扩展 t
}
样例: acwing 844. 走迷宫
给定一个 n×m 的二维整数数组,用来表示一个迷宫,数组中只包含 0 或 1,其中 0 表示可以走的路,1 表示不可通过的墙壁。
最初,有一个人位于左上角 (1,1) 处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。
请问,该人从左上角移动至右下角 (n,m) 处,至少需要移动多少次。
数据保证 (1,1) 处和 (n,m) 处的数字为 0,且一定至少存在一条通路。
输入格式
第一行包含两个整数 n 和 m。
接下来 n 行,每行包含 m 个整数(0 或 1),表示完整的二维数组迷宫。
输出格式
输出一个整数,表示从左上角移动至右下角的最少移动次数。
数据范围
1≤n,m≤100
输入样例:
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
输出样例:
8
思路:
- 用g[][] 存储地图, 用d[][] 存储起点到n,m 的距离
- 从起点开始广度优先遍历地图
- 当地图遍历完,就求出了起点到各点的距离,输出d[n][m]即可

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int g[N][N]; // 存储地图
int d[N][N]; // 存储距离
int n, m;
int bfs()
{
queue<PII> q;
q.push({
0, 0});
memset(d, -1, sizeof d);
d[0][0] = 0;
while(!q.empty())
{
PII start = q.front();
q.pop();
g[start.first][start.second] = 1; // 表示已经走过
int dx[4] = {
-1, 0, 1, 0}, dy[4] = {
0, 1, 0 ,-1};
for(int i =0; i < 4; i++)
{
int x = start.first + dx[i], y = start.second + dy[i];
if(!g[x][y] && x >= 0 && x < n && y >= 0 && y < m && d[x][y] == -1) // 表示没有走过,说明可以选择
{
g[x][y] = 1;
d[x][y] = d[start.first][start.second] + 1;
//cout << d[x][y] << endl;
q.push({
x, y});
}
}
}
// d 数组中已经保存着能走的路径最短距离(到{0,0})
return d[n - 1][m - 1];
}
int main()
{
cin >> n >> m;
memset(g, 1, sizeof g); // 需要初始化都不能走
for(int i = 0; i < n; i ++)
for(int j =0; j < m; j ++)
cin >> g[i][j];
cout << bfs() << endl;
return 0;
}
下面是如果想输出走的路径代码
思路: 从最后的位置倒着输出
方法: 用Pre[][] 保存上一个点的位置信息
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int g[N][N]; // 存储地图
int d[N][N]; // 存储距离
int n, m;
PII Pre[N][N]; // 保存走过的点
int bfs()
{
queue<PII> q;
q.push({
0, 0});
memset(d, -1, sizeof d);
d[0][0] = 0;
while(!q.empty())
{
PII start = q.front();
q.pop();
g[start.first][start.second] = 1; // 表示已经走过
int dx[4] = {
-1, 0, 1, 0}, dy[4] = {
0, 1, 0 ,-1};
for(int i =0; i < 4; i++)
{
int x = start.first + dx[i], y = start.second + dy[i];
if(!g[x][y] && x >= 0 && x < n && y >= 0 && y < m && d[x][y] == -1) // 表示没有走过,说明可以选择
{
g[x][y] = 1;
Pre[x][y] = start;
d[x][y] = d[start.first][start.second] + 1;
//cout << d[x][y] << endl;
q.push({
x, y});
}
}
}
// 下面是从最后将路径输出出来
int x = n - 1, y = m - 1;
while(x || y)
{
cout << x << ' ' << y << endl;
auto t = Pre[x][y];
x = t.first, y= t.second;
}
// d 数组中已经保存着能走的路径最短距离(到{0,0})
return d[n - 1][m - 1];
}
int main()
{
cin >> n >> m;
memset(g, 1, sizeof g); // 需要初始化都不能走
for(int i = 0; i < n; i ++)
for(int j =0; j < m; j ++)
cin >> g[i][j];
cout << bfs() << endl;
return 0;
}
运行结果如下:
边栏推荐
- 接口自动化测试实践指导(中):接口测试场景有哪些
- Mongo shell, the most complete mongodb in history
- Mathematical analysis_ Notes_ Chapter 10: integral with parameters
- 掌握软件安全测试方法秘笈,安全测试报告信手捏来
- 测试/开发程序员怎么升职?从无到有,从薄变厚.......
- What if the win11 screenshot key cannot be used? Solution to the failure of win11 screenshot key
- 赠票速抢|行业大咖纵论软件的质量与效能 QECon大会来啦
- Have you got the same "artifact" of cross architecture development praised by various industry leaders?
- buildroot的根文件系统提示“depmod:applt not found”
- EasyCVR无法使用WebRTC进行播放,该如何解决?
猜你喜欢

Formation continue en robotique (automatisation) - 2022 -

Five years of automated testing, and finally into the ByteDance, the annual salary of 30W is not out of reach

buildroot的根文件系统提示“depmod:applt not found”

Kivy tutorial of setting the size and background of the form (tutorial includes source code)

Win11控制面板快捷键 Win11打开控制面板的多种方法

Common methods of list and map

见到小叶栀子

Optimization of channel status offline of other server devices caused by easycvr cluster restart

DAB-DETR: DYNAMIC ANCHOR BOXES ARE BETTER QUERIES FOR DETR翻译

How to solve the problem of adding RTSP device to easycvr cluster version and prompting server ID error?
随机推荐
The most complete deployment of mongodb in history
Nanopineo use development process record
Web3 社区中使用的术语
SQL where multiple field filtering
Kotlin compose text supports two colors
Fix the problem that the highlight effect of the main menu disappears when the easycvr Video Square is clicked and played
How to write a resume that shines in front of another interviewer [easy to understand]
Mongo shell, the most complete mongodb in history
How to open win11 remote desktop connection? Five methods of win11 Remote Desktop Connection
微信能开小号了,拼多多“砍一刀”被判侵权,字节VR设备出货量全球第二,今日更多大新闻在此
Deeply cultivate the developer ecosystem, accelerate the innovation and development of AI industry, and Intel brings many partners together
2022 electrician cup question B analysis of emergency materials distribution under 5g network environment
What if the win11 screenshot key cannot be used? Solution to the failure of win11 screenshot key
Pyqt5 out of focus monitoring no operation timer
各路行业大佬称赞的跨架构开发“神器”,你get同款了吗?
SSM+JSP实现企业管理系统(OA管理系统源码+数据库+文档+PPT)
軟件測試之網站測試如何進行?測試小攻略走起!
This "advanced" technology design 15 years ago makes CPU shine in AI reasoning
Formation continue en robotique (automatisation) - 2022 -
[leetcode]Spiral Matrix II