图论Day37:深搜基础

深搜三部曲(回溯法)

cpp 复制代码
vector<int> result;
vector<int> path;

void dfs(图, 当前节点){
    if(终点){
        result.push_back(path);
        return;
    }
    for(遍历相邻节点) {
        path.push_back(节点);
        dfs(图, 节点);
        path.pop()//回溯
    }
}

98. 可达路径

cpp 复制代码
#include<iostream>
#include<vector>
using namespace std;

vector<vector<int>> result;
vector<int> path;
void dfs(vector<vector<int>> graph, int cur, int N) {
    if(cur == N) {
        result.push_back(path);
        return;
    }
    for(int i = 1; i <= N; i++){
        if(graph[cur][i] == 0){
            continue;
        }
        path.push_back(i);
        dfs(graph, i, N);
        path.pop_back();
    }
}
int main() {
    int N, M;
    cin >> N >> M;

    vector<vector<int>> graph (N + 1, vector<int>(N + 1, 0));
    while(M--){
        int x, y;
        cin >> x >> y;
        graph[x][y] = 1;
    }
    path.push_back(1);
    dfs(graph, 1, N);

    if (result.size() == 0) cout << -1 << endl;
    for (const vector<int> &pa : result) {
        for (int i = 0; i < pa.size() - 1; i++) {
            cout << pa[i] << " ";
        }
        cout << pa[pa.size() - 1]  << endl;
    }
}
相关推荐
青山木1 小时前
Hot 100 --- 岛屿数量
java·数据结构·算法·leetcode·深度优先·广度优先
稚南城才子,乌衣巷风流3 小时前
DFS序详解:原理、应用与实现
算法·深度优先·图论
zander2584 小时前
114. 二叉树展开为链表
数据结构·链表·深度优先
wabs6663 天前
关于图论【深度优先搜索的理论基础】
算法·深度优先·图论
Zachery Pole3 天前
CCF-CSP备战NO.6【栈】
算法·深度优先
网络与设备以及操作系统学习使用者3 天前
生成树防环,Super-VLAN省IP,端口安全护网络
运维·网络·学习·深度优先
Jayden_Ruan4 天前
C++组合的输出
c++·算法·深度优先
山峰哥11 天前
数据库工程与索引策略实战指南‌
服务器·数据库·sql·oracle·深度优先
Tisfy11 天前
LeetCode 2685.统计完全连通分量的数量:DFS求每个连通块的边点数
算法·leetcode·深度优先··题解·连通图·全连通分量
青山木11 天前
Hot 100 --- 二叉树与递归
java·数据结构·算法·leetcode·深度优先