首页 > 编程语言 > 详细

DAG图的拓扑排序 python

时间:2014-05-22 23:11:06      阅读:835      评论:0      收藏:0      [点我收藏+]

在DAG中DFS中顶点的出栈顺序即逆拓扑序。

bubuko.com,布布扣


def topological_sort( graph ):

    is_visit = dict( ( node, False ) for node in graph )
    li = []

    def dfs( graph, start_node ):
        
        for end_node in graph[start_node]:
            if not is_visit[end_node]:
                is_visit[end_node] = True
                dfs( graph, end_node )
        li.append( start_node )
    
    for start_node in graph:
        if not is_visit[start_node]:
            is_visit[start_node] = True
            dfs( graph, start_node )

    li.reverse()
    return li
    
            
if __name__ == '__main__':
    graph = {
        'v1': ['v5'],
        'v2': ['v1'],
        'v3': ['v1', 'v5'],
        'v4': ['v2', 'v5'],
        'v5': [],
    }
    li = topological_sort( graph )
    print li


DAG图的拓扑排序 python,布布扣,bubuko.com

DAG图的拓扑排序 python

原文:http://blog.csdn.net/pandora_madara/article/details/26478385

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!