Topological Sorting vs Depth First Traversal (DFS)
In DFS, we print a vertex and then recursively call DFS for its adjacent vertices. In topological sorting, we need to print a vertex before its adjacent vertices.
Ex) In the given graph, the vertex '5' should be printed before vertex '0', but unlike DFS, the vertex '4' should also be printed before vertex '0'. So Topological sorting is different from DFS.
A DFS of the shown graph is "5 2 3 1 0 4", but it is not a topological sorting.
Algorithm to find Topological Sorting
We can modify DFS to find Topological Sorting of a graph. In DFS, we start from a vertex, we first print it and then recursively call DFS for its adjacent vertices. In topological sorting, we use a temporary stack. We don't print the vertex immediately, we first recursively call topological sorting for all its adjacent vertices, then push it to a stack. Finally, print contents of stack.
Note that a vertex is pushed to stack only when all of its adjacent vertices (and their adjacent vertices and so on) are already in stack.
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 | 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 helper(self, v, visited, stack) : visited[v] = True for i in self.graph[v] : if visited[i] == False : self.helper(i, visited, stack) stack.append(v) def topologicalSort(self) : visited = [False]*self.V stack = [] for i in range(self.V) : if visited[i] == False: self.helper(i, visited, stack) while stack: print(stack.pop()) | cs |
Time Complexity
The above algorithm is simply DFS with an extra stack. So time complexity is same as DFS which is O(V+E).
References:
https://www.geeksforgeeks.org/topological-sorting/
'0 > algorithm' 카테고리의 다른 글
중복 있는 순열 (0) | 2019.03.20 |
---|---|
중복 없는 순열 (0) | 2019.03.17 |
How to approach most of DP problems (House Robber) (0) | 2019.02.14 |
Kth Largest Element in an Array (in Python) / Quick select (0) | 2019.02.11 |
회전된 배열에서의 검색 (이진 탐색) (0) | 2019.02.10 |