File tree Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Original file line number Diff line number Diff line change
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 ()
You can’t perform that action at this time.
0 commit comments