Skip to content

Commit 7af153e

Browse files
author
Partho Biswas
committed
no message
1 parent fad19b6 commit 7af153e

File tree

1 file changed

+66
-1
lines changed

1 file changed

+66
-1
lines changed

algoexpert.io/python/River_Sizes.py

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# https://www.algoexpert.io/questions/River%20Sizes
22

3-
3+
# Approach 1: Using BFS
44
# O(wh) time | O(wh) space
55
def river_size(matrix):
66
size = [] # It would contain all of our river sizes
@@ -47,3 +47,68 @@ def get_unvisited_neighbours(i, j, matrix, visited):
4747

4848

4949

50+
# Approach 2: Using Disjoin Sets
51+
class DJS(object):
52+
def __init__(self, numOfElements):
53+
self.n = numOfElements
54+
self.parents = [0 for _ in range(numOfElements)]
55+
self.rank = [0 for _ in range(numOfElements)]
56+
self.makeSet()
57+
58+
def makeSet(self):
59+
for i in range(self.n):
60+
self.parents[i] = i
61+
62+
def union(self, x, y):
63+
parentX = self.find(x)
64+
parentY = self.find(y)
65+
if parentX == parentY:
66+
return
67+
if self.rank[parentX] > self.rank[parentY]:
68+
self.parents[parentY] = parentX
69+
elif self.rank[parentX] < self.rank[parentY]:
70+
self.parents[parentX] = parentY
71+
else:
72+
self.parents[parentX] = parentY
73+
self.rank[parentY] += 1
74+
75+
def find(self, x):
76+
parentX = self.parents[x]
77+
if x != parentX:
78+
parentX = self.find(parentX)
79+
return parentX
80+
81+
82+
from collections import defaultdict
83+
def riverSizes(matrix):
84+
if not matrix:
85+
return []
86+
rowCount, colCount = len(matrix), len(matrix[0])
87+
djs = DJS(rowCount * colCount)
88+
for i in range(rowCount):
89+
for j in range(colCount):
90+
val = matrix[i][j]
91+
if val == 0:
92+
continue
93+
94+
if i + 1 < rowCount and matrix[i + 1][j] == 1:
95+
djs.union(i * (colCount) + j, (i + 1) * (colCount) + j)
96+
97+
if i - 1 >= 0 and matrix[i - 1][j] == 1:
98+
djs.union(i * (colCount) + j, (i - 1) * (colCount) + j)
99+
100+
if j + 1 < colCount and matrix[i][j + 1] == 1:
101+
djs.union(i * (colCount) + j, (i) * (colCount) + j + 1)
102+
103+
if j - 1 >= 0 and matrix[i][j - 1] == 1:
104+
djs.union(i * (colCount) + j, (i) * (colCount) + j - 1)
105+
106+
ilands = defaultdict(int)
107+
for i in range(rowCount):
108+
for j in range(colCount):
109+
if matrix[i][j] == 1:
110+
val = i * colCount + j
111+
parent = djs.find(val)
112+
ilands[parent] += 1
113+
114+
return ilands.values()

0 commit comments

Comments
 (0)