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 72 73 74 75 76 77 78 79 80 81 82
| from typing import List import sys
class Solution1: def findCircleNum(self, isConnected: List[List[int]]) -> int: visited = set()
def dfs(item): visited.add(item) for item1 in range(len(isConnected)): if isConnected[item][item1] and item1 not in visited: dfs(item1)
number_of_circles = 0 for item in range(len(isConnected)): if item not in visited: number_of_circles += 1 dfs(item)
return number_of_circles
class DSU: def __init__(self, length): self.par = list(range(length)) self.rank = [1] * length self.size = 1
def find(self, u): if u != self.par[u]: self.par[u] = self.find(self.par[u]) return self.par[u]
def union(self, u, v): uu, vv = self.find(u), self.find(v) if uu == vv: return False if self.rank[uu] > self.rank[vv]: self.par[vv] = uu elif self.rank[vv] > self.rank[uu]: self.par[uu] = vv else: self.par[uu] = vv self.rank[vv] += 1 self.size += 1 return True
class Solution2:
def isConnected(self, u, v, isConnected): return isConnected[u][v] == 1
def findCircleNum(self, isConnected: List[List[int]]) -> int: length_isConnected = len(isConnected) union_find = DSU(length_isConnected) if not isConnected: return 0 for u in range(length_isConnected): for v in range(u, length_isConnected): if self.isConnected(u, v, isConnected): union_find.union(u, v) return len(set([union_find.find(i) for i in range(length_isConnected)]))
s1 = Solution1() s2 = Solution2()
while True: try: rows = int(input("Rows: ")) cols = int(input("Columns: ")) matrix = [] for i in range(rows): row_input = input(f'Elements in row {i + 1}: ') row = list(map(int, row_input.split())) matrix.append(row) for row in range(len(matrix)): for col in range(len(matrix[0])): if matrix[row][col] != 0 and matrix[row][col] != 1: raise ValueError except ValueError: print("Input is not a 0 1 matrix") sys.exit() print(s1.findCircleNum(matrix), s2.findCircleNum(matrix))
|