是的,可以通过定义记录入度为 0 的数组,将入度为 0 的点压入栈中,然后使用深度优先搜索(DFS)算法实现拓扑序列的输出。

以下是一个示例的 C++ 代码实现:

#include <iostream>
#include <vector>
#include <stack>

using namespace std;

vector<vector<int>> adj; // 邻接表
vector<int> indegree; // 记录入度为 0 的点
vector<bool> visited; // 记录节点是否已经访问
stack<int> result; // 存储拓扑序列的栈

void dfs(int node) {
    visited[node] = true;

    for (int neighbor : adj[node]) {
        if (!visited[neighbor]) {
            dfs(neighbor);
        }
    }

    result.push(node); // 将当前节点压入栈中
}

vector<int> topologicalSort(int numNodes) {
    for (int i = 0; i < numNodes; i++) {
        if (indegree[i] == 0) {
            dfs(i);
        }
    }

    vector<int> sortedNodes;
    while (!result.empty()) {
        sortedNodes.push_back(result.top());
        result.pop();
    }

    return sortedNodes;
}

int main() {
    int numNodes, numEdges;
    cout << 'Enter the number of nodes and edges: ';
    cin >> numNodes >> numEdges;

    adj.resize(numNodes);
    indegree.resize(numNodes, 0);
    visited.resize(numNodes, false);

    cout << 'Enter the edges: ' << endl;
    for (int i = 0; i < numEdges; i++) {
        int u, v;
        cin >> u >> v;
        adj[u].push_back(v);
        indegree[v]++;
    }

    vector<int> sortedNodes = topologicalSort(numNodes);

    cout << 'Topological order: ';
    for (int node : sortedNodes) {
        cout << node << ' ';
    }
    cout << endl;

    return 0;
}

该代码首先输入节点数和边数,然后输入每条边的起点和终点,构建邻接表和计算每个节点的入度。然后通过调用topologicalSort函数实现拓扑排序,最后输出拓扑序列。

注意,上述代码假设节点从 0 开始编号。如果节点编号从 1 开始,需要适当修改代码。

C++ 实现拓扑排序:使用 DFS 算法和入度为 0 的节点

原文地址: https://www.cveoy.top/t/topic/pcvU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录