-
Notifications
You must be signed in to change notification settings - Fork 0
/
Detect Cycle using DSU.py
63 lines (32 loc) · 1.22 KB
/
Detect Cycle using DSU.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
53
54
55
56
57
58
59
60
61
62
63
class Solution:
def findparent(self, vertex, parent):
if vertex == parent[vertex]:
return vertex
parent[vertex] = self.findparent(parent[vertex], parent)
return parent[vertex]
def detectCycle(self, n, adj):
parent = [i for i in range(n)]
depth = [1 for _ in range(n)]
mp = {}
for i in range(n):
for j in range(len(adj[i])):
a = i
b = adj[i][j]
if (a, b) in mp or (b, a) in mp:
continue
mp[(a, b)] = 1
a_parent = self.findparent(a, parent)
b_parent = self.findparent(b, parent)
if a_parent != b_parent:
if depth[a_parent] > depth[b_parent]:
parent[b_parent] = a_parent
depth[a_parent] += depth[b_parent]
elif depth[a_parent] < depth[b_parent]:
parent[a_parent] = b_parent
depth[b_parent] += depth[a_parent]
else:
parent[a_parent] = b_parent
depth[b_parent] += depth[a_parent]
else:
return 1
return 0