Lintcode 127. Topological Sorting (Medium) Python

本文详细介绍了如何使用拓扑排序算法解决有向无环图的排序问题。通过统计节点的入度,将入度为0的节点加入队列,再进行广度优先搜索,最终实现对图中节点的正确排序。

题目:https://www.lintcode.com/problem/topological-sorting/description
思路:拓扑排序
1.统计所有点的入度
2.将入度为0的加入队列
3.bfs

"""
Definition for a Directed graph node
class DirectedGraphNode:
    def __init__(self, x):
        self.label = x
        self.neighbors = []    # 存的是DirectedGraphNode
# len(graph) 得到node的个数
"""

class Solution:
    """
    @param: graph: A list of Directed graph node
    @return: Any topological order for the given graph.
    """
    def topSort(self, graph):
        # write your code here
        if graph == None :
            return []
        
        indegree = self.indegreehelper(graph)
        queue = [] 
        for i in range(len(graph)):
            if indegree[i][0] == 0:
                 queue.append(graph[i])
        result = []
        hashtable = set()
        while queue :
            current = queue.pop(0)
            result.append(current)
            for i in indegree[current.label][1]:
                indegree[i.label][0] -= 1
                if indegree[i.label][0] == 0:
                    queue.append(graph[i.label])
        return result
        
    def indegreehelper(self,graph):
        indegree = [[0,[]] for x in range(len(graph))]
        print indegree
        for i in range(len(graph)):
            for j in graph[i].neighbors:
                indegree[j.label][0] += 1
            indegree[i][1] = graph[i].neighbors
        return indegree
            
            
                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值