Skip to content

Commit 9d00444

Browse files
committedJun 30, 2017
Topological Sort
1 parent 742a130 commit 9d00444

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
 

‎Graph/P05_TopologicalSort.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# Author: OMKAR PATHAK
2+
3+
# Time Complexity: O(|V| + |E|)
4+
# One important point to remember is that topological sort can be applied only to acyclic graph.
5+
6+
class Graph():
7+
def __init__(self, count):
8+
self.vertex = {}
9+
self.count = count # vertex count
10+
11+
# for printing the Graph vertexes
12+
def printGraph(self):
13+
for i in self.vertex.keys():
14+
print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]]))
15+
16+
# for adding the edge beween two vertexes
17+
def addEdge(self, fromVertex, toVertex):
18+
# check if vertex is already present,
19+
if fromVertex in self.vertex.keys():
20+
self.vertex[fromVertex].append(toVertex)
21+
else:
22+
# else make a new vertex
23+
self.vertex[fromVertex] = [toVertex]
24+
self.vertex[toVertex] = []
25+
26+
def topologicalSort(self):
27+
visited = [False] * self.count # Marking all vertices as not visited
28+
stack = [] # Stack for storing the vertex
29+
for vertex in range(self.count):
30+
# Call the recursive function only if not visited
31+
if visited[vertex] == False:
32+
self.topologicalSortRec(vertex, visited, stack)
33+
34+
print(' '.join([str(i) for i in stack]))
35+
# print(stack)
36+
37+
# Recursive function for topological Sort
38+
def topologicalSortRec(self, vertex, visited, stack):
39+
40+
# Mark the current node in visited
41+
visited[vertex] = True
42+
43+
# mark all adjacent nodes of the current node
44+
try:
45+
for adjacentNode in self.vertex[vertex]:
46+
if visited[adjacentNode] == False:
47+
self.topologicalSortRec(adjacentNode, visited, stack)
48+
except KeyError:
49+
return
50+
51+
# Push current vertex to stack which stores the result
52+
stack.insert(0,vertex)
53+
54+
if __name__ == '__main__':
55+
g= Graph(6)
56+
g.addEdge(5, 2)
57+
g.addEdge(5, 0)
58+
g.addEdge(4, 0)
59+
g.addEdge(4, 1)
60+
g.addEdge(2, 3)
61+
g.addEdge(3, 1)
62+
# g.printGraph()
63+
g.topologicalSort()
64+
65+
# OUTPUT:
66+
# 5 4 2 3 1 0

0 commit comments

Comments
 (0)
Please sign in to comment.