开发者社区> 问答> 正文

Python 拓扑排序

Python 拓扑排序

展开
收起
游客ejnn55cgkof5g 2020-02-14 19:42:24 4651 0
1 条回答
写回答
取消 提交回答
  • 
    from collections import defaultdict 
     
    class Graph: 
        def __init__(self,vertices): 
            self.graph = defaultdict(list) 
            self.V = vertices
      
        def addEdge(self,u,v): 
            self.graph[u].append(v) 
      
        def topologicalSortUtil(self,v,visited,stack): 
      
            visited[v] = True
      
            for i in self.graph[v]: 
                if visited[i] == False: 
                    self.topologicalSortUtil(i,visited,stack) 
      
            stack.insert(0,v) 
      
        def topologicalSort(self): 
            visited = [False]*self.V 
            stack =[] 
      
            for i in range(self.V): 
                if visited[i] == False: 
                    self.topologicalSortUtil(i,visited,stack) 
      
            print (stack) 
      
    g= Graph(6) 
    g.addEdge(5, 2); 
    g.addEdge(5, 0); 
    g.addEdge(4, 0); 
    g.addEdge(4, 1); 
    g.addEdge(2, 3); 
    g.addEdge(3, 1); 
      
    print ("拓扑排序结果:")
    g.topologicalSort()
    执行以上代码输出结果为:
    
    拓扑排序结果:
    [5, 4, 2, 3, 1, 0]
    2020-02-14 19:42:44
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载