当前位置:网站首页>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;
}
运行结果如下:
边栏推荐
- Kotlin Compose Text支持两种颜色
- Use facet to record operation log
- The easycvr platform is connected to the RTMP protocol, and the interface call prompts how to solve the error of obtaining video recording?
- The worse the AI performance, the higher the bonus? Doctor of New York University offered a reward for the task of making the big model perform poorly
- Ssm+jsp realizes the warehouse management system, and the interface is called an elegant interface
- Formation continue en robotique (automatisation) - 2022 -
- In cooperation with the research team of the clinical trial center of the University of Hong Kong and Hong Kong Gangyi hospital, Kexing launched the clinical trial of Omicron specific inactivated vacc
- 程序员上班摸鱼,这么玩才高端!
- Pyqt5 out of focus monitoring no operation timer
- 2022 electrician cup a question high proportion wind power system energy storage operation and configuration analysis ideas
猜你喜欢

Hardware development notes (10): basic process of hardware development, making a USB to RS232 module (9): create ch340g/max232 package library sop-16 and associate principle primitive devices

EasyCVR平台接入RTMP协议,接口调用提示获取录像错误该如何解决?

Imitate Tengu eating the moon with Avatar

用CPU方案打破内存墙?学PayPal堆傲腾扩容量,漏查欺诈交易量可降至1/30

The easycvr platform is connected to the RTMP protocol, and the interface call prompts how to solve the error of obtaining video recording?

On the 110th anniversary of Turing's birth, has the prediction of intelligent machine come true?

【自动化经验谈】自动化测试成长之路

Mongo shell, the most complete mongodb in history

各路行业大佬称赞的跨架构开发“神器”,你get同款了吗?

程序员上班摸鱼,这么玩才高端!
随机推荐
mpf2_线性规划_CAPM_sharpe_Arbitrage Pricin_Inversion Gauss Jordan_Statsmodel_Pulp_pLU_Cholesky_QR_Jacobi
[multi threading exercise] write a multi threading example of the producer consumer model.
Both primary and secondary equipment numbers are 0
Continuous learning of Robotics (Automation) - 2022-
赠票速抢|行业大咖纵论软件的质量与效能 QECon大会来啦
See Gardenia minor
Intel and Xinbu technology jointly build a machine vision development kit to jointly promote the transformation of industrial intelligence
这项15年前的「超前」技术设计,让CPU在AI推理中大放光彩
每人每年最高500万经费!选人不选项目,专注基础科研,科学家主导腾讯出资的「新基石」启动申报
【线段树实战】最近的请求次数 + 区域和检索 - 数组可修改+我的日程安排表Ⅰ/Ⅲ
Fix the problem that the highlight effect of the main menu disappears when the easycvr Video Square is clicked and played
EasyUI export excel cannot download the method that the box pops up
【自动化经验谈】自动化测试成长之路
SQL where multiple field filtering
buildroot的根文件系统提示“depmod:applt not found”
Analysis on the thinking of college mathematical modeling competition and curriculum education of the 2022a question of the China Youth Cup
NanopiNEO使用开发过程记录
过气光刻机也不能卖给中国!美国无理施压荷兰ASML,国产芯片再遭打压
未婚夫捐5亿美元给女PI,让她不用申请项目,招150位科学家,安心做科研!
Case reward: Intel brings many partners to promote the innovation and development of multi domain AI industry