[Lintcode]127. Topological Sorting

127. Topological Sorting

  • 本题难度: Medium
  • Topic: Search & Recursion

Description

Given an directed graph, a topological order of the graph nodes is defined as follow:

For each directed edge A -> B in graph, A must before B in the order list.
The first node in the order can be any node in the graph with no nodes direct to it.
Find any topological order for the given graph.

Example
For graph as follow:

picture

The topological order can be:

[0, 1, 2, 3, 4, 5]
[0, 2, 3, 1, 5, 4]
...
Challenge
Can you do it in both BFS and DFS?

Clarification
Learn more about representation of graphs

Notice
You can assume that there is at least one topological order in the graph.

我的代码

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

class Solution:
    """
    @param graph: A list of Directed graph node
    @return: A list of integer
    """
    def topSort(self, graph):
        res = []
        indegree = self.get_indegree(graph)
        queue = collections.deque([i for i in graph if indegree[i] == 0])
        while(queue):
            node  = queue.popleft()
            res.append(node)
            for neighbor in node.neighbors:
                indegree[neighbor] -= 1
                if indegree[neighbor] == 0:
                    queue.append(neighbor)
        return res
                        
                
        
        
        
    def get_indegree(self,graph):
        #dictionary for indegree
        indegree_table = {node:0 for node in graph}
        for node in graph:
            for neighbor in node.neighbors:
                indegree_table[neighbor] += 1
        return indegree_table
        
        
        
    #     node_to_indegree = self.get_indegree(graph)

    #     # bfs
    #     order = []
    #     start_nodes = [n for n in graph if node_to_indegree[n] == 0]
    #     queue = collections.deque(start_nodes)
    #     while queue:
    #         node = queue.popleft()
    #         order.append(node)
    #         for neighbor in node.neighbors:
    #             node_to_indegree[neighbor] -= 1
    #             if node_to_indegree[neighbor] == 0:
    #                 queue.append(neighbor)
                
    #     return order
    
    # def get_indegree(self, graph):
    #     node_to_indegree = {x: 0 for x in graph}

    #     for node in graph:
    #         for neighbor in node.neighbors:
    #             node_to_indegree[neighbor] += 1
                
    #     return node_to_indegree

思路

  1. 之前很少用过python的colletction集成模块
  • namedtuple 规定名称和变量个数的tuple
  • deque 栈/队列
  • defaultdict key不存在时返回默认值(之前用过)
  • OrderedDict
  • Counter
  1. 拓扑排序
    一开始理解得不太深刻。
    主要是根据入度来定。
  • 时间复杂度
  • 出错

猜你喜欢

转载自www.cnblogs.com/siriusli/p/10381504.html
今日推荐