-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopologicalSort.py
More file actions
46 lines (32 loc) · 1.12 KB
/
Copy pathTopologicalSort.py
File metadata and controls
46 lines (32 loc) · 1.12 KB
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
# Created by Roshan Jayswal
# Copyright © 2021 AppMillers. All rights reserved.
from collections import defaultdict
class Graph:
def __init__(self, numberofVertices):
self.graph = defaultdict(list)
self.numberofVertices = numberofVertices
def addEdge(self, vertex, edge):
self.graph[vertex].append(edge)
def topogologicalSortUtil(self, v, visited, stack):
visited.append(v)
for i in self.graph[v]:
if i not in visited:
self.topogologicalSortUtil(i, visited, stack)
stack.insert(0, v)
def topologicalSort(self):
visited = []
stack = []
for k in list(self.graph):
if k not in visited:
self.topogologicalSortUtil(k, visited, stack)
print(stack)
customGraph = Graph(8)
customGraph.addEdge("A", "C")
customGraph.addEdge("C", "E")
customGraph.addEdge("E", "H")
customGraph.addEdge("E", "F")
customGraph.addEdge("F", "G")
customGraph.addEdge("B", "D")
customGraph.addEdge("B", "C")
customGraph.addEdge("D", "F")
customGraph.topologicalSort()