簡體   English   中英

使用DFS對二維vestor構成的有向圖進行拓撲排序

[英]Topological sort for directed graph made of two-dimensional vestor using DFS

這是我在 int_main 中創建有向圖的方法:

int edges, vertices;

    cout << "Number of edges" << endl;
    cin >> edges;

    cout << "Number of verticles" << endl;
    cin >> vertices;

    vector<vector<int>> graph(vertices); 

    int a, b;
    for (int i = 0; i < edges; i++) {
        cin >> a >> b; 
        graph[a].push_back(b);
    }

我的任務是使用 DFS 對有向圖進行拓撲排序。 這是我嘗試實現 DFS 和拓撲排序的方式:

void dfs(vector<vector<int>> &graph, vector<bool> &used, int nodeIndex) {
    used[nodeIndex] = true;
    for (auto i : graph[nodeIndex]) {
        if (!used[i])
            dfs(graph, used, i);
    }
}

void topologicalSort(vector<vector<int>> &graph, vector<bool> &used, int nodeIndex) {
    vector<int> answer;
    for (int i = 0; i < graph.size(); i++)
        used[nodeIndex] = false;
    answer.clear();
    for (int i = 0; i < graph.size(); ++i)
        if (!used[i])
            dfs(graph, used, i);
    reverse(answer.begin(), answer.end());
}

但是拓撲排序似乎不起作用,我不明白我應該怎么做才能解決這個問題。

您需要在最后傳遞 arguments 和push_back(nodeIndex)中的答案:

void dfs(vector<vector<int>> &graph, vector<bool> &used, int nodeIndex, vector<int> &answer) {
    used[nodeIndex] = true;
    for (auto i : graph[nodeIndex]) {
        if (!used[i])
            dfs(graph, used, i);
    }
    answer.push_back(nodeIndex);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM