classSolution: defnumIslands(self, grid) -> int: ifnot grid: return0 uf = UnionFind(grid) directions = [(0,1), (0,-1), (-1,0), (1,0)] n, m = len(grid), len(grid[0]) for i in range(n): for j in range(m): if grid[i][j] == '1': for x, y in directions: if0 <= i+x < n and0 <= j+y < m and grid[i+x][j+y] == '1': uf.union(i*m+j, (i+x)*m+(j+y)) return uf.count
defunion(self, x, y): rootx = self.find(x) rooty = self.find(y) if rootx != rooty: self.parent[rooty] = rootx defdiff_groups(self): diff_groups = set() for i in range(self.n): diff_groups.add(self.find(i)) return len(diff_groups)
classSolution: deffindCircleNum(self, M) -> int: uf = UnionFind(M) for i in range(len(M)): for j in range(len(M)): if M[i][j]: uf.union(i, j) return uf.diff_groups()
classSolution: deffindCircleNum(self, M: List[List[int]]) -> int: ifnot M: return0 self.M, self.n, self.visited, count = M, len(M), set(), 0 for i in range(self.n): if i notin self.visited: count += 1 self.dfs(i) return count defdfs(self, i): for j in range(self.n): if self.M[i][j] == 1and j notin self.visited: self.visited.add(j) self.dfs(j)
第三种方法:BFS,把上面的DFS的递归写法改成BFS的队列即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
from collections import deque classSolution: deffindCircleNum(self, M: List[List[int]]) -> int: ifnot M: return0 n, visited, count, queue = len(M), set(), 0, deque() for i in range(n): if i notin visited: count += 1 queue.append(i) while queue: p = queue.popleft() visited.add(p) for j in range(n): if M[p][j] == 1and j notin visited: queue.append(j) return count