跳到正文

个人记录

DFS 深度优先搜索 - 「深搜」

limingx约 5 分钟
原文

这是 2026年4月10日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2026年4月10日
更新
2026年5月23日
篇幅
约 5 分钟

版本

  1. v3当前
  2. v2
  3. v1

深度优先搜索(DFS)是一种遍历 / 搜索算法,核心逻辑为:

  • 以树形结构为基础展开搜索
  • 优先处理当前元素的所有子元素,直到无法继续深入
  • 回溯到同级别的下一个元素,重复上述过程

本质就是:不撞南墙不回头,一条路走到底,再回头换路

省流:深度优先搜索,通常是以树形结构出现的,其宗旨为:优先处理先出现的元素,等到此元素不可能出现更多的可能(子元素)再处理同级别的元下一个元素。

经常玩旮旯给木的同学肯定知道,旮旯给木通常都有很多种结局,你的每一次决定都会影响结局。

旮旯给木(?

相信大家已经理解了什么是深度优先搜索。

那就开始写题吧(

先看题:P2089 烤鸡

因为它一定只有 1010 种调料,每种调料最多只有三个,优先考虑 O(310)O(3^{10}) 做法,每种操作做完后判断美味度够不够即可,足够就输出。 anti-ai[]

代码
C++
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
int s1[100],s2[100],s3[100],s4[100],s5[100],s6[100],s7[100],s8[100],s9[100],s10[100];
int top=1;
int n;
int main(){
	cin>>n;
	for(int a1=1;a1<=3;a1++){
		for(int a2=1;a2<=3;a2++){
			for(int a3=1;a3<=3;a3++){
				for(int a4=1;a4<=3;a4++){
					for(int a5=1;a5<=3;a5++){
						for(int a6=1;a6<=3;a6++){
							for(int a7=1;a7<=3;a7++){
								for(int a8=1;a8<=3;a8++){
									for(int a9=1;a9<=3;a9++){
										for(int a10=1;a10<=3;a10++){
											if(a1+a2+a3+a4+a5+a6+a7+a8+a9+a10==n){
												s1[top]=a1;
												s2[top]=a2;
												s3[top]=a3;
												s4[top]=a4;
												s5[top]=a5;
												s6[top]=a6;
												s7[top]=a7;
												s8[top]=a8;
												s9[top]=a9;
												s10[top]=a10;
												top+=1;
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
	cout<<top-1<<endl;
	for(int i=1;i<=top-1;i++){
		cout<<s1[i]<<" "<<s2[i]<<" "<<s3[i]<<" "<<s4[i]<<" "<<s5[i]<<" "<<s6[i]<<" "<<s7[i]<<" "<<s8[i]<<" "<<s9[i]<<" "<<s10[i]<<endl; 
	}
	return 0;
}

显然一坨屎。

好的,这个时候我们来写刚刚学习的深度优先搜索。首先,这是一个函数式的算法,也就是自己调用自己。

  • 从第 11 个配料开始
  • 依次尝试 11 克、22 克、33 克
  • 每选一种,就递归进入下一个配料
  • 等选满 1010 个配料时,判断总和是否等于 nn
  • 满足就记录方案,不满足就直接回溯

这就是典型的回溯 + 深度优先:一条路走到选满 1010 个,再回头换一种选择,继续往下搜。

代码
C++
#include<iostream>
using namespace std;
int n; // 目标美味值
int res[15],ans[60000][15];
int cnt=0;// 方案计数器
void dfs(int deep,int num){
    if(deep==11){ // 选完10种配料
        if(num==n){
            cnt++;
            for(int i=1;i<=10;i++)  ans[cnt][i]=res[i]; // 保存方案
        }
        return;
    }
    for(int i=1;i<=3;i++){ // 枚举 1~3g 
        res[deep]=i;
        dfs(deep+1,num+i);
    }
}

int main(){
    cin>>n;
    dfs(1,0);
    cout<<cnt<<endl;
    for(int i=1;i<=cnt;i++){
        cout<<ans[i][1];
        for(int j=2;j<=10;j++)
        cout<<' '<<ans[i][j];
        cout<<endl;
    }
    return 0;
}