|
1 | 1 | # https://www.algoexpert.io/questions/River%20Sizes
|
2 | 2 |
|
3 |
| - |
| 3 | +# Approach 1: Using BFS |
4 | 4 | # O(wh) time | O(wh) space
|
5 | 5 | def river_size(matrix):
|
6 | 6 | size = [] # It would contain all of our river sizes
|
@@ -47,3 +47,68 @@ def get_unvisited_neighbours(i, j, matrix, visited):
|
47 | 47 |
|
48 | 48 |
|
49 | 49 |
|
| 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