自学内容网 自学内容网

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

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


797.所有可能的路径

题目链接

解题过程

  • 用dfs遍历每一个边

力扣

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

#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;
    }
}

原文地址:https://blog.csdn.net/qq_61552256/article/details/142901399

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!