图论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;
    }
}
相关推荐
Momo__zz2 小时前
零代码平台设计
算法·深度优先
山峰哥7 小时前
VB事件驱动编程实战:从零到一搭建完整管理系统
前端·数据库·性能优化·深度优先·vb
江屿风7 小时前
C++图论基础最小生成树经典OJ题流食般投喂
开发语言·c++·笔记·算法·深度优先·图论
CQU_JIAKE1 天前
6.5aaaaa
算法·深度优先
AZaLEan__1 天前
图论:拓扑排序
算法·深度优先
木井巳3 天前
【DFS解决floodfill算法】岛屿数量
java·算法·leetcode·深度优先
兰令水4 天前
leecodecode【回溯子集】【2026.6.4打卡-java版本】
java·开发语言·深度优先
星马梦缘6 天前
死锁与进程资源分配问题的解法
算法·操作系统·深度优先·死锁
ʚ希希ɞ ྀ6 天前
全排列 --- 回溯
算法·leetcode·深度优先
Lsk_Smion7 天前
力扣实训 _ [200].岛屿数量
算法·leetcode·深度优先