当前位置:网站首页>深度优先搜索(dfs)简介
深度优先搜索(dfs)简介
2022-07-27 05:04:00 【竹林居士-】
深度优先搜索(Deep first serch,简称dfs)是基于递归的一种搜索方式。
从名字就可以看出,它是按深度方向搜索的。也就是说,直接选一条路到底,接着再选一条路。
看图

程序执行顺序如图上数字所标,先走一列到底,再选一条路。
例题:
原题
http://ybt.ssoier.cn:8088/problem_show.php?pid=1317【题目描述】
排列与组合是常用的数学方法,其中组合就是从n个元素中抽出r个元素(不分顺序且r≤n),我们可以简单地将n个元素理解为自然数1,2,…,n,从中任取r个数。
现要求你用递归的方法输出所有组合。
例如n=5,r=3,所有组合为:
1 2 3 1 2 4 1 2 5 1 3 4 1 3 5 1 4 5 2 3 4 2 3 5 2 4 5 3 4 5
【输入】
行两个自然数n、r(1<n<21,1≤r≤n)。
【输出】
所有的组合,每一个组合占一行且其中的元素按由小到大的顺序排列,每个元素占三个字符的位置,所有的组合也按字典顺序。
【输入样例】
5 3
【输出样例】
123
124
125
134
135
145
234
235
245
345
审题:这道题第一个数从1开始,一直枚举到3(因为要求字典序),剩下的数依次枚举即可
做法:
1.定义变量、dfs函数
int n,r,res[30];
void dfs(int num,int pre)//声明函数
{
if(num>r)//如果枚举的数超过r,输出
{
for(int i=1;i<=r;i++) printf("%3d",res[i]);//每个元素占三个字符
cout<<endl;
return;
}
for(int i=pre+1;i<=n;i++)
{
res[num]=i;
dfs(num+1,i);//递归
}
}
2.输入,传参
int main()
{
cin>>n>>r;
dfs(1,0);//第一层
return 0;
}完整代码:
#include<bits/stdc++.h>
using namespace std;
int n,r,res[30];
void dfs(int num,int pre)//声明函数
{
if(num>r)//如果枚举的数超过r,输出
{
for(int i=1;i<=r;i++) printf("%3d",res[i]);//每个元素占三个字符
cout<<endl;
return;
}
for(int i=pre+1;i<=n;i++)
{
res[num]=i;
dfs(num+1,i);//递归
}
}
int main()
{
cin>>n>>r;
dfs(1,0);//第一层
return 0;
}新手,请多多指导
边栏推荐
- 分享一道关于程序编译过程的选择题(内含编译过程浅谈,符号表的形成合并过程)
- Share a multiple-choice question about the process of program compilation (including a brief discussion on the compilation process, the formation and merging process of symbol tables)
- 后台订单管理
- GalleryCMS下载安装与配置
- 自我理解思考
- 2021 Niuke multi school training camp 5 (question b)
- JS中是如何使用for..of来遍历对象
- 【codeforces 1695C Zero Path】DP
- JS中如何判断一个对象是空对象
- Redis cluster
猜你喜欢

Share a multiple-choice question about define (including the replacement rules, program environment and preprocessing related knowledge of define during precompiling)

First knowledge of C language -- what is C language

C WPF uses listbox to implement ruler control

权限的配置,组件传值

Share a multiple-choice question about the process of program compilation (including a brief discussion on the compilation process, the formation and merging process of symbol tables)

DNSmasq使用总结

流程控制-分支

2021 Niuke multi school training camp 5 (question b)

eval与assert执行一句话木马

Program environment and preprocessing (Part 1): how does a program run successfully?
随机推荐
权限展示-左侧列表动态化
C语言函数入门介绍
2021 Niuke multi school training camp 5 (question b)
sql_mode严格模式(ANSI/TRADITIONAL/STRICT_TRANS_TABLES)
First acquaintance with C language - first acquaintance with pointer
Initial C language -- the function of keyword static
JS==操作符的强制类型转换规定
md5 密码加密
初识C语言——常量、变量
Redis persistence
GCC 编译选项
【codeforces round#800 B. Paranoid String】DP
后台实现spu管理
思考一些文件的作用
退出登录与jsx显示
弹性盒/伸缩盒(flex)的使用
流程控制-分支
flask项目配置
初识C语言——常见的数据类型
JS中arguments类数组