代码随想录算法训练营第五十五天| 图论入门

今天入门图论的基本理论,做了深度优先遍历图的例子


797.所有可能的路径

题目链接

解题过程

  • 用dfs遍历每一个边

力扣

cpp 复制代码
class Solution {
public:
    vector<vector<int>>result;
    vector<int>path;
    void dfs(vector<vector<int>>& graph) {
        if (path.back() == graph.size() - 1) {
            result.push_back(path);
            return;
        }
        int points = path.back();
        for (int point : graph[points]) {
            path.push_back(point);
            dfs(graph);
            path.pop_back();
        }
    }

    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
        path.push_back(0);
        dfs(graph);
        return result;
    }
};

ACM

cpp 复制代码
#include<iostream>
#include<vector>
#include<list>
using namespace std;
int n, m;
vector<vector<int>>result;
vector<int>path;
void dfs(vector<list<int>>&graph) {
    if (path.back() == n) {
        result.push_back(path);
        return;
    }
    int point = path.back();
    for (int i : graph[point]) {
        path.push_back(i);
        dfs(graph);
        path.pop_back();
    }
}

int main() {
    cin >> n >> m;
    vector<list<int>>graph(n + 1);
    while (m--) {
        int s, t;
        cin >> s >> t;
        graph[s].push_back(t);
    }
    path.push_back(1);
    dfs(graph);
    if (result.size() == 0) cout << -1 << endl;
    for (vector<int>vec : result) {
        for (int i = 0; i < vec.size() - 1; i++) {
            cout << vec[i] << " ";
        }
        cout << vec.back() << endl;
    }
}
相关推荐
运器12318 分钟前
【一起来学AI大模型】支持向量机(SVM):核心算法深度解析
大数据·人工智能·算法·机器学习·支持向量机·ai·ai编程
Zedthm27 分钟前
LeetCode1004. 最大连续1的个数 III
java·算法·leetcode
神的孩子都在歌唱1 小时前
3423. 循环数组中相邻元素的最大差值 — day97
java·数据结构·算法
YuTaoShao1 小时前
【LeetCode 热题 100】73. 矩阵置零——(解法一)空间复杂度 O(M + N)
算法·leetcode·矩阵
dying_man2 小时前
LeetCode--42.接雨水
算法·leetcode
vortex52 小时前
算法设计与分析 知识总结
算法
艾莉丝努力练剑3 小时前
【C语言】学习过程教训与经验杂谈:思想准备、知识回顾(三)
c语言·开发语言·数据结构·学习·算法
ZZZS05163 小时前
stack栈练习
c++·笔记·学习·算法·动态规划
hans汉斯3 小时前
【人工智能与机器人研究】基于力传感器坐标系预标定的重力补偿算法
人工智能·算法·机器人·信号处理·深度神经网络
vortex55 小时前
算法设计与分析:分治、动态规划与贪心算法的异同与选择
算法·贪心算法·动态规划