图论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 小时前
深搜练习(组合)(5)
c++·算法·深度优先·力扣
踩坑记录4 小时前
leetcode hot100 64. 最小路径和 medium 递归优化
leetcode·深度优先
westdata-Tm5 小时前
洛谷P1219 [USACO1.5] 八皇后 Checker Challenge
算法·深度优先·dfs
葳_人生_蕤7 小时前
hot100——回溯和DFS、BFS
算法·深度优先
故事和你919 小时前
洛谷-算法2-4-字符串2
开发语言·数据结构·c++·算法·深度优先·动态规划·图论
万添裁10 小时前
huawei 机考
算法·华为·深度优先
Mr_pyx1 天前
【LeetHOT100】随机链表的复制——Java多解法详解
算法·深度优先
superior tigre1 天前
78 子集
算法·leetcode·深度优先·回溯
.5482 天前
DFS + BFS(深度优先搜索 & 广度优先搜索)
算法·深度优先·宽度优先
凌波粒2 天前
LeetCode--二叉树前中后序遍历的递归与迭代实现(二叉树/DFS)
算法·leetcode·深度优先