卖萌的弱渣

I am stupid, I am hungry.

Topological Sorting

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

Notice

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

Solution

  • Time: O(n)
(Topological-Sorting.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Definition for a Directed graph node
# class DirectedGraphNode:
#     def __init__(self, x):
#         self.label = x
#         self.neighbors = []

class Solution:
    def topSort(self, graph):
        indegree = {}
        ret = []
        queue = []
        # indegree <graphnode, degree> 
        for x in graph:
            indegree[x] = 0
        # count indegree
        for i in graph:
            for j in i.neighbors:
                indegree[j] = indegree[j]+1
        # find the starer
        for i in graph:
            if indegree[i] == 0:
                ret.append(i)
                queue.append(i)
        # bfs: use queue (use bfs in my code)
        # dfs: use recursive
        while len(queue) != 0:
            cur = queue[0]
            queue.pop(0)
            for i in cur.neighbors:
                indegree[i] -= 1
                if indegree[i] == 0:
                    ret.append(i)
                    queue.append(i)
        return ret