zoukankan      html  css  js  c++  java
  • Topological Sorting拓扑排序

    定义:

    Topological Sorting is a method of arranging the vertices in a directed acyclic graph (DAG有向无环图) as a sequence, such that for every directed edge(u,v), 即u-> v, vertex u comes before v in the ordering

    注意:

    • A topological ordering is possible if and only if the graph has no directed cycles
    • Topological orderings are NOT unique

    应用场景:

    • build systems:  a program cannot be built unless its dependencies are first built 
    • pre-requisite problems: a course cannot be selected unless its pre-requisite courses are taken 
    • dependency problems
    • task schedule

    时间复杂度:

    O(V+E) 

    Topological Sort(){
        1. Call DFS to compute finish time f[v] for each vertex
        2. At each vertex is finished, insert it onto the front of a linked list
        3. Return the linked list of vertices
    }

     内部原理:

    比如从任意一个vertex出发(比如,随便选个NodeH), 来DFS搜索

    从NodeH出发,DFS可以走 NodeH-> NodeJ

    从NodeJ出发, DFS可以 NodeJ -> NodeM

    发现NodeM后面没有元素了, 我们把NodeM放到Stack里面(基于Stack的FILO特性)

    从NodeM往回走,到NodeJ, 从NodeJ出发,DFS可以NodeJ-> NodeL

    发现NodeL后面没有元素了, 我们把NodeL放到Stack里面

    以此类推,DFS走完整个有向无环图,并用Stack保证了u-> v, vertex u comes before v in the ordering

    综上,

    1. 从有向无环图的任意点出发

    2. 进行DFS搜索, 直到搜到当前元素已经"nowhere left to go"了

    3. 将该元素放到Stack里,并将该元素mark为visited

    4. 从该元素backtrack,继续DFS 

  • 相关阅读:
    PHP 使用 ElasticSearch
    PHP面试题目
    MySQL取得某一范围随机数
    Git版本控制的基本命令
    PHP中array_merge和array相加的区别分析
    nginx服务器常见错误代码500、501、502、503、504、505
    Laravel小项目之第4节 Laravel-通过表单实现新增及操作状态提示功能
    前端基础 jQuery
    前端基础 DOM & BOM
    前端基础 & 初识JS(JavaScript)
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10487164.html
Copyright © 2011-2022 走看看