Skip to content

Commit 97fdb55

Browse files
authored
Merge pull request #237 from jsourabh1/patch-1
Topological sort
2 parents dd5f5c4 + 699a15f commit 97fdb55

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

Graph/Khan_algo.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
'''
2+
author :saurabh jain
3+
to find whether a graph has a cycle or not not
4+
if not than print the topological sorting for them
5+
'''
6+
from collections import defaultdict
7+
8+
9+
class solution:
10+
11+
def __init__(self, vrt):
12+
self.vrt = vrt
13+
self.graph = defaultdict(list)
14+
15+
def edges(self, u, v):
16+
global vertex,indegree
17+
self.graph[u].append(v)
18+
if u not in indegree.keys():
19+
indegree[u]=0
20+
if v not in indegree.keys():
21+
indegree[v]=1
22+
23+
else:
24+
indegree[v]+=1
25+
vertex.add(u)
26+
vertex.add(v)
27+
28+
def topological(self):
29+
global vertex,indegree
30+
q=[]
31+
count=0
32+
for i in vertex:
33+
if indegree[i]==0:
34+
q.append(i)
35+
36+
result=[]
37+
38+
while q:
39+
40+
current=q.pop(0)
41+
count+=1
42+
result.append(current)
43+
44+
45+
46+
for i in self.graph[current]:
47+
indegree[i]-=1
48+
if indegree[i]==0:
49+
q.append(i)
50+
51+
if count!=len(vertex):
52+
print("there is no topolical string ")
53+
else:
54+
print(result)
55+
56+
57+
58+
return
59+
60+
61+
62+
63+
64+
indegree=defaultdict()
65+
vertex=set()
66+
67+
g =solution(6)
68+
g.edges(5, 2);
69+
g.edges(5, 0);
70+
g.edges(4, 0);
71+
g.edges(4, 1);
72+
g.edges(2, 3);
73+
g.edges(3, 1)
74+
print(indegree)
75+
print(vertex)
76+
77+
g.topological()

0 commit comments

Comments
 (0)