跳到正文

算法·理论

算法与数据结构(四):DFS(深度优先搜索)

ILearnedSomeCoding约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年3月20日
收录
2025年12月12日
更新
2026年11月20日
篇幅
约 3 分钟

版本

  1. v1当前

深度优先搜索(简称深搜)是一种搜索算法,特点是会一直向深搜,直到到达底层,然后再往上一层去找下一个节点继续搜。 这里是P2677 [USACO07DEC] Bookshelf 2 B的解法,因为没有找到纯粹DFS,所以就用这个了。请不要抄袭。

C++
#include<bits/stdc++.h>
using namespace std;
int n, b, m = 2e9, p[25], c[25];
void dfs(int s){
	if(s > n){
		int h = 0;
		for(int i = 1;i <= n;i++){
			p[i]?h += c[i]:int();
		}
		if(h >= b)m = min(m, h);
		h = 0;
		return;                                                                            
	}
	p[s] = 1;
	dfs(s + 1);
	p[s] = 0;
	dfs(s + 1);
}
int main(){
	cin >> n >> b;
	for(int i = 1;i <= n;i++)cin >> c[i];
	dfs(1);
	cout << m - b;
	return 0;
}

这里真正重要的就这几行:

C++
void dfs(int s){
	if(s > n){
		// 检验结果
		return;
	}
	p[s] = 1; // 用
	dfs(s + 1); // 搜索
	p[s] = 0; // 不用
	dfs(s + 1); //搜索
}

s代表step,意思是搜索的深度。p代表plan,意思是计划。p数组搜到最后会存储结果。这里,p[i]是0就说明不用,否则就用。
这里其实是搜索n个0或1的组合,其实也可以用来搜索别的每个都有固定的选项的搜索。

如果要求全排列怎么办呢?

题目:全排列问题。 先上代码:

C++
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

int n, p[13], f[13];

void dfs(int s) {
    if (s == n + 1) {
        for (int i = 1; i <= n; i++) {
            cout.width(5);
            cout << p[i];
        }
        cout << "\n";
        return;
    }
    for (int i = 1; i <= n; i++) {
        if (!f[i]) {
            f[i] = 1;
            p[s] = i;
            dfs(s + 1);
            f[i] = 0;
        }
    }
}

int main() {
    cin >> n;
    dfs(1);
    return 0;
}

这里开了第二个数组f,f[i]用来存储i有没有用过。这里就不过多解释细节了。就是枚举1∼n1 \sim n然后如果没用过就标记,搜索,用过了就不管。

原文