北美程序员面试干货

LintCode 127 [Topological Sortin

2016-07-10  本文已影响81人  Jason_Yuan

原题

给定一个有向图,图节点的拓扑排序被定义为:
对于每条有向边A--> B,则A必须排在B之前  
拓扑排序的第一个节点可以是任何在图中没有其他节点指向它的节点  
找到给定图的任一拓扑排序

样例
对于下列图:

Graph

这个图的拓扑排序可能是:
[0, 1, 2, 3, 4, 5]
或者
[0, 2, 3, 1, 5, 4]
或者
....

解题思路

完整代码

# Definition for a Directed graph node
# class DirectedGraphNode:
#     def __init__(self, x):
#         self.label = x
#         self.neighbors = []
import Queue

class Solution:
    """
    @param graph: A list of Directed graph node
    @return: A list of integer
    """
    def topSort(self, graph):
        result = []
        visited = {}
        # BFS - calculate the in-degree for each node
        for node in graph:
            for neighbor in node.neighbors:
                if neighbor in visited:
                    visited[neighbor] += 1
                else:
                    visited[neighbor] = 1
                
        q = Queue.Queue()
        # enqueue the node which in-degree == 0
        for node in graph:
            if node not in visited:
                q.put(node)
                result.append(node)
        
        while not q.empty():
            node = q.get()
            for neighbor in node.neighbors:
                visited[neighbor] -= 1
                if visited[neighbor] == 0:
                    q.put(neighbor)
                    result.append(neighbor)
                    
        return result
上一篇 下一篇

猜你喜欢

热点阅读