-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTopological_Sort.py
52 lines (39 loc) · 1.05 KB
/
Topological_Sort.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
49
50
51
52
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 2 17:43:26 2017
@author: ska
Topological Sorting: Used for Directed Acyclic Graph(DAG)
"""
def topoSort():
visited = [False]*V
stack = []
for i in range(V):
if visited[i] == False:
topoUtil(i, visited, stack)
print(stack)
def topoUtil(v, visited, stack):
visited[v] = True
# print(v)
for i in g[v]:
if visited[i] == False:
topoUtil(i, visited, stack)
stack.insert(0,v)
#==============================================================================
#Implementation of Graph
#==============================================================================
from collections import defaultdict
g = defaultdict(list)
def addEdge(a,b):
g[a].append(b)
#==============================================================================
# implementation of example
#==============================================================================
addEdge(5, 2);
addEdge(5, 0);
addEdge(4, 0);
addEdge(4, 1);
addEdge(2, 3);
addEdge(3, 1);
V = 6 #total no. of virtices
topoSort()