10/16/2018 Topological Sort (Directed Acyclic Graph)

本文深入探讨了拓扑排序的概念及其实现算法,特别是在有向无环图(DAG)中的应用。介绍了通过深度优先搜索(DFS)进行节点访问并生成拓扑排序列表的方法,以及如何检测图中是否存在环。此外,还提供了示例代码,展示了如何生成单一的拓扑排序,以及如何寻找所有可能的拓扑排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Topological Sort: Topological sort of a Directed Acyclic Graph (DAG) is a linear ordering of the vertices in the DAG so that vertex u comes before vertex v if the edge (u -> v) exists in the DAG. Every DAG has least one and possibly more topological sort(s). 

Description of the algorithm: 

1. visit a node and its connecting point (directed) by using dfs. After visiting, push nodes you visited in a list and delete them as well as their related paths.

2. Do step 1 for every node in your graph, and the result list is the result of the topological sort.

Comment: In dfs2(u), we append u to the back of a list of explored vertices only after visiting all the subtrees below u in the DFS spanning tree (the connection to DFS). This will be in reversed order, but we can work around this issue by reversing the print order in the output phase. 

Runtime for the above code snippet: O(V + E) -> same as DFS

The above code just generates the one topographical sort. What if we want all possible topographical sorts? 

eg. Ordering Tasks, Uva 10395

假设有n个变量,还有m个二元组(u, v),分别表示变量u小于v。那么,所有变量从小到大排列到大起来应该是什么样子的呢?例如,假设有四个变量a, b, c, d,若已知a < b, c < b, d < c, 则这四个变量的排序的可能是a < b < c < d。尽管还有其他可能 (如 d < a < c < b),你只需要找出其中一个即可。

 

分析: 把每个变量看出一个点,“小于”关系看成有向边,则得到了一个有向图。这样,我们的任务实际上是把一个图的所有结点排序,使得每一条有向边(u, v) 对应的u都排在v的前面。若图中存在有向环,则不存在拓扑排序。(在本例中,如果 a < b, b < c, a > c, 则有环,但是不可能)在访问完一个结点之后把它加到当前拓扑排序的首部。

class TopologicalSort {
    static int[] c;
    static int[] topo;
    static boolean[][] g;
    static int t;
    public void fill(boolean[][] graph) {
        for (int i = 0; i < graph.length; i++) {
            for (int j = 0; j < graph[0].length; j++) {
                g[i][j] = graph[i][j];
            }
        }
        t = graph.length;
    }
    public static boolean dfs(int u) {
        c[u] = -1;
        for (int i = 0; i < c.length; i++) {
            // u -> i has an edge from u to i; notice that topological sort is in non-cycle directed graph
            if (g[u][i] == true) {
                if (c[i] < 0) return false; //there is a cycle
                if (c[i] == 0 && !dfs(i)) return false; //the remaining dfs also works fine
            }
            c[u] = 1; topo[--t] = u;
            return true;
        }
    }

    public static boolean toposort() {
        for (int u = 0; u < g.length; u++) {
            if (!dfs(u)) return false;
        }
        return true;
    }
}

Comment: can use the above algorithm to test if there is a cycle in the graph

<think>我们被要求使用中文回答,并且需要遵循严格的格式要求。 用户的问题是关于networkx库中`nx.topological_sort()`函数的使用和示例。 根据引用,我们知道NetworkX是一个用于复杂网络的Python库,而拓扑排序是有向无环图(DAG)中节点的一种线性排序,使得对于每一条有向边(u, v),节点u都出现在节点v之前。 我们将按照以下步骤回答: 1. 解释拓扑排序的概念。 2. 介绍`nx.topological_sort()`函数的基本用法。 3. 提供一个完整的示例代码,包括创建有向图、进行拓扑排序以及输出结果。 4. 注意:在示例代码中,我们将使用NetworkX创建一个小型的有向无环图。 同时,根据系统指令,我们需要生成相关问题。 注意:在回答中,我们引用了NetworkX官方文档(引用[1]和引用[3]),因此会在适当的地方添加引用标识。 开始回答:</think>### NetworkX 中 `nx.topological_sort()` 函数的使用与示例 拓扑排序是针对**有向无环图(DAG)** 的节点线性排序算法,使得对于任意有向边 \((u \to v)\),节点 \(u\) 总出现在节点 \(v\) 之前。`nx.topological_sort()` 是 NetworkX 库中实现该算法的核心函数[^1]。 --- #### **基本用法** ```python import networkx as nx # 创建有向图 G = nx.DiGraph() edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D")] G.add_edges_from(edges) # 拓扑排序 sorted_nodes = list(nx.topological_sort(G)) print(sorted_nodes) # 输出:['A', 'C', 'B', 'D'] 或 ['A', 'B', 'C', 'D'](合法排序不唯一) ``` - **输入要求**:图必须为有向无环图(DAG),若图含环会抛出 `NetworkXUnfeasible` 异常。 - **返回值**:节点的拓扑排序列表(可能有多个合法结果,函数返回其中一种)。 --- #### **完整示例:课程依赖关系排序** 假设课程依赖关系如下: - 数据结构依赖编程基础 - 算法依赖数据结构 - 机器学习依赖算法和数学 ```python import networkx as nx # 定义课程依赖图 G = nx.DiGraph() G.add_edges_from([ ("编程基础", "数据结构"), ("数据结构", "算法"), ("算法", "机器学习"), ("数学", "机器学习") ]) # 拓扑排序(确保无循环依赖) try: course_order = list(nx.topological_sort(G)) print("课程学习顺序:", course_order) except nx.NetworkXUnfeasible: print("图中存在循环依赖,无法排序!") # 输出示例:['数学', '编程基础', '数据结构', '算法', '机器学习'] ``` --- #### **关键注意事项** 1. **检测环**:排序前可用 `nx.is_directed_acyclic_graph(G)` 验证是否为 DAG。 2. **多结果处理**:若需所有可能排序,使用 `list(nx.all_topological_sorts(G))`。 3. **性能**:时间复杂度 \(O(V+E)\)(\(V\) 为节点数,\(E\) 为边数),适合大型图处理[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值