Skip to content

Commit 2940ccd

Browse files
committed
Create number-of-connected-components-in-an-undirected-graph.ot
1 parent 02a4f95 commit 2940ccd

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Time: O(nlog*n) ~= O(n), n is the length of the positions
2+
# Space: O(n)
3+
4+
class UnionFind(object):
5+
def __init__(self, n):
6+
self.set = range(n)
7+
self.count = n
8+
9+
def find_set(self, x):
10+
if self.set[x] != x:
11+
self.set[x] = self.find_set(self.set[x]) # path compression.
12+
return self.set[x]
13+
14+
def union_set(self, x, y):
15+
x_root, y_root = map(self.find_set, (x, y))
16+
if x_root != y_root:
17+
self.set[min(x_root, y_root)] = max(x_root, y_root)
18+
self.count -= 1
19+
20+
21+
class Solution(object):
22+
def countComponents(self, n, edges):
23+
"""
24+
:type n: int
25+
:type edges: List[List[int]]
26+
:rtype: int
27+
"""
28+
union_find = UnionFind(n)
29+
for i, j in edges:
30+
union_find.union_set(i, j)
31+
return union_find.count

0 commit comments

Comments
 (0)