-
Notifications
You must be signed in to change notification settings - Fork 0
/
UnionFindGraphical.py
72 lines (47 loc) · 1.38 KB
/
UnionFindGraphical.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
64
65
66
67
68
69
70
71
# check cycles in graph using union find
# weighted tree balancing added along with path compress
class graph:
def __init__(self):
self.graph = {}
self.parents = {}
self.size = {}
def addnode(self, key1, key2, edge=0):
if key1 not in self.graph:
self.graph[key1] = {}
if key2 not in self.graph:
self.graph[key2] = {}
self.graph[key1][key2] = edge
def getparent(self, vertex):
while self.parents[vertex] != -1:
vertex = self.parents[vertex]
return vertex
def union(self, vertex, neighbour):
x_par = self.getparent(vertex)
y_par = self.getparent(neighbour)
if self.size[x_par] <= self.size[y_par]:
self.parents[x_par] = y_par
self.size[y_par] += self.size[x_par]
else:
self.parents[y_par] = x_par
self.size[x_par] += self.size[y_par]
def findcycle(self):
result = []
for key in self.graph:
self.parents[key] = -1
self.size[key] = 1
for vertex in self.graph:
for neighbour in self.graph[vertex]:
x_par = self.getparent(vertex)
y_par = self.getparent(neighbour)
if x_par == y_par:
return True
self.union(x_par, y_par)
g = graph()
g.addnode(0, 1)
g.addnode(2, 3)
g.addnode(4,2)
g.addnode(4,1)
if g.findcycle():
print ("Graph contains cycle")
else :
print ("Graph does not contain cycle ")