Lintcode 127. Topological Sorting

Given an directed graph, a topological order of the graph nodes is defined as follow:

  • For each directed edge A -> B in graph, A must before B in the order list.
  • The first node in the order can be any node in the graph with no nodes direct to it.

Find any topological order for the given graph.

 Notice

You can assume that there is at least one topological order in the graph.

Example

For graph as follow:

picture

The topological order can be:

[0, 1, 2, 3, 4, 5]
[0, 2, 3, 1, 5, 4]
...
题目思路:

这题就是topological sorting的算法之一:我使用dfs。

实现的是链接的算法--topological sorting

class Solution {
public:
    /*
     * @param graph: A list of Directed graph node
     * @return: Any topological order for the given graph.
     */
    vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*>& graph) {
        // write your code here
        vector<DirectedGraphNode*> res;
        set<int> visited;
    
        if(graph.size()==0)
            return graph;
        
        for(int i=0;i<graph.size();i++){
            if(visited.find(graph[i]->label) == visited.end())
                topSort(res, visited, graph[i]);
        }
        
        reverse(res.begin(), res.end());
        return res;
    }
    
private:
    void topSort(vector<DirectedGraphNode*>& res,
            set<int>& visited, DirectedGraphNode* node){
                
        if(visited.find(node->label) != visited.end())
            return;
           
        visited.insert(node->label);
        for(int i=0; i < node->neighbors.size(); i++){
            topSort(res, visited, node->neighbors[i]);
        }
        res.push_back(node);
    }

};

这种方法需要保证的是,第0个节点一定要是入度为零的节点,否则会出错。

第二种方法采用的是使用map统计所有节点的入度节点,然后使用queue保存入度为零的节点,最后使用bfs。

class Solution {
public:
    /**
     * @param graph: A list of Directed graph node
     * @return: Any topological order for the given graph.
     */
    vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*> graph) {
        // write your code here
        int size = graph.size(), i = 0;
        if(size <= 0) {
            return vector<DirectedGraphNode*>();
        }

        vector<DirectedGraphNode*> result;
        queue<DirectedGraphNode*> noPreNode;
        map<DirectedGraphNode*, int> nodeIndegree;

        getIndegree(graph, nodeIndegree);

        for(i=0; i<size; i++) {
            if(nodeIndegree[graph[i]] == 0) {
                noPreNode.push(graph[i]);
            }
        }

        while(!noPreNode.empty()) {
            result.push_back(noPreNode.front());
            for(i=0; i<noPreNode.front()->neighbors.size(); i++) {
                if(--nodeIndegree[noPreNode.front()->neighbors[i]] == 0) {
                    noPreNode.push(noPreNode.front()->neighbors[i]);
                }
            }
            noPreNode.pop();
        }
        return result;
    }

    void getIndegree(vector<DirectedGraphNode*> &graph, map<DirectedGraphNode*, int> &nodeIndegree) {
        int size = graph.size();
        for(int i=0; i<size; i++) {
            int size2 = graph[i]->neighbors.size();
            for(int j=0; j<size2; j++) {
                nodeIndegree[graph[i]->neighbors[j]]++;
            }
        }
    }
};


<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]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值