图论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;
    }
}
相关推荐
垆边人似月.2 天前
删边使每个连通块权值和为 target
算法·深度优先·图论
垆边人似月.4 天前
华为题:矩阵中的最长递增路径
算法·深度优先
无忧.芙桃5 天前
图的精髓:邻接矩阵与遍历全解析
c++·算法·面试·深度优先·广度优先
垆边人似月.7 天前
华为题:全排列
算法·深度优先·图论
有毒的教程9 天前
Dev-C++ 避免爆栈(Stack Overflow)完整方案
c++·算法·深度优先
一条大祥脚10 天前
26ICPC网络赛第二场 计数|DFS|MEX|贪心
算法·深度优先·mex·icpc网络赛
yi01111 天前
DAY22: LeetCode 733:图像渲染——从二维网格开始理解 DFS 和 BFS
数据结构·笔记·python·算法·leetcode·深度优先·宽度优先
CQU_JIAKE14 天前
10.3【A】
深度优先
言乐614 天前
Python区分广度优先深度优先宽度优先的区别
python·算法·深度优先·广度优先·宽度优先
RobinDevNotes15 天前
大模型3D并行训练怎么配才不浪费算力
网络·人工智能·深度学习·深度优先