forked from DURepo/CS_325_Exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graph-topologicalSort.py
48 lines (33 loc) · 1.21 KB
/
Graph-topologicalSort.py
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from collections import defaultdict
class Graph:
# Constructor
def __init__(self, vertices):
self.graph = defaultdict(list)
self.vertices = vertices
def addEdge(self, u, v):
self.graph[u].append(v)
def helperFunction(myGraph, currentNode, visited, result):
visited[currentNode] = True # Mark the current node as visited
# Recur for all the adjacent vertices of currentNode
for i in myGraph.graph[currentNode]:
if visited[i] == False:
helperFunction(myGraph, i, visited, result)
result.insert(0, currentNode) # Push current vertex to result
def topologicalSort(myGraph):
visited = [False] * myGraph.vertices # Mark all the vertices as not visited
result = [] # Our stack to store the result/output
for currentNode in range(myGraph.vertices):
if visited[currentNode] == False:
helperFunction(myGraph, currentNode, visited, result)
return (result)
# Driver code
# Create a graph given in the above diagram
myGraph = Graph(5)
myGraph.addEdge(0, 1)
myGraph.addEdge(0, 3)
myGraph.addEdge(1, 2)
myGraph.addEdge(2, 3)
myGraph.addEdge(2, 4)
myGraph.addEdge(3, 4)
print("Topological Sort")
print(topologicalSort(myGraph))