算法基础模板——DFS与BFS算法

本文深入解析了DFS(深度优先搜索)与BFS(宽度优先搜索)两种经典算法的特点与应用。从数据结构、空间复杂度到解决的具体问题类型,详细对比了两者的差异。通过具体代码实例,如全排列问题、N皇后问题及走迷宫问题,展示了DFS的回溯与剪枝策略,以及BFS在最短路径问题上的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

算法基础模板——DFS与BFS算法

1. DFS与BFS算法的比较

​ 这两种算法一般都是解决树与图的遍历,主要的区别如下

算法数据结构空间复杂度有无固定模板解决哪一类问题
DFSstackO(h)枚举所有的可能,一般有回溯与剪枝
BFSqueueO(2^h)有最短概念,最少的次数
2.DFS

​ DFS内有固定的模板,主要是思路,比较常见的问题有全排列问题

  1. 全排列问题
#include <iostream>

using namespace std;

const int N = 10;

int n;
int path[N],state[N];

void dfs(int u)
{
    if (u == n)
    {
        for (int i = 0; i < n; i ++ ) printf("%d ", path[i]);
        puts("");

        return;
    }

    for (int i = 1; i <= n; i ++ )
        if (!state[i])
        {
            path[u] = i ;
            state[i] = true;
            dfs(u + 1);
            state[i] = false;
        }
}

int main()
{
    scanf("%d", &n);

    dfs(0, 0);

    return 0;
}
  1. N皇后问题

    第一种搜索顺序

#include <iostream>

using namespace std;

const int N = 10;

int n;
bool row[N], col[N], dg[N * 2], udg[N * 2];
char g[N][N];

void dfs(int x, int y, int s)
{
    if (s > n) return;
    if (y == n) y = 0, x ++ ;

    if (x == n)
    {
        if (s == n)
        {
            for (int i = 0; i < n; i ++ ) puts(g[i]);
            puts("");
        }
        return;
    }

    g[x][y] = '.';
    dfs(x, y + 1, s);

    if (!row[x] && !col[y] && !dg[x + y] && !udg[x - y + n])
    {
        row[x] = col[y] = dg[x + y] = udg[x - y + n] = true;
        g[x][y] = 'Q';
        dfs(x, y + 1, s + 1);
        g[x][y] = '.';
        row[x] = col[y] = dg[x + y] = udg[x - y + n] = false;
    }
}

int main()
{
    cin >> n;

    dfs(0, 0, 0);

    return 0;
}

​ 第二种搜索顺序

#include <iostream>

using namespace std;

const int N = 20;

int n;
char g[N][N];
bool col[N], dg[N], udg[N];

void dfs(int u)
{
    if (u == n)
    {
        for (int i = 0; i < n; i ++ ) puts(g[i]);
        puts("");
        return;
    }

    for (int i = 0; i < n; i ++ )
        if (!col[i] && !dg[u + i] && !udg[n - u + i])
        {
            g[u][i] = 'Q';
            col[i] = dg[u + i] = udg[n - u + i] = true;
            dfs(u + 1);
            col[i] = dg[u + i] = udg[n - u + i] = false;
            g[u][i] = '.';
        }
}

int main()
{
    cin >> n;
    for (int i = 0; i < n; i ++ )
        for (int j = 0; j < n; j ++ )
            g[i][j] = '.';

    dfs(0);

    return 0;
}
3. BFS

​ 注意只有最权重为1的最短路问题才能够使用宽搜

1、 模板

queue <-初始状态
while(queue不为空){
	将队头拿出来
	扩展队列
}

2、 例子

  1. 走迷宫

    #include <cstring>
    #include <iostream>
    #include <algorithm>
    #include <queue>
    
    using namespace std;
    
    typedef pair<int, int> PII;
    
    const int N = 110;
    
    int n, m;
    int g[N][N], d[N][N];
    
    int bfs()
    {
        queue<PII> q;
    
        memset(d, -1, sizeof d);
        d[0][0] = 0;
        q.push({0, 0});
    
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
    
        while (q.size())
        {
            auto t = q.front();
            q.pop();
    
            for (int i = 0; i < 4; i ++ )
            {
                int x = t.first + dx[i], y = t.second + dy[i];
    
                if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1)
                {
                    d[x][y] = d[t.first][t.second] + 1;
                    q.push({x, y});
                }
            }
        }
    
        return d[n - 1][m - 1];
    }
    
    int main()
    {
        cin >> n >> m;
        for (int i = 0; i < n; i ++ )
            for (int j = 0; j < m; j ++ )
                cin >> g[i][j];
    
        cout << bfs() << endl;
    
        return 0;
    }
    
参考:

作者:yxc
链接:https://www.acwing.com/activity/content/code/content/47097/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值