deffind(self, x): while x != self.parent[x]: # 路径压缩 self.parent[x] = self.parent[self.parent[x]] x = self.parent[x] return x defis_connected(self, p, q): return self.find(p) == self.find(q)
classSolution: defnumIslands(self, grid: List[List[str]]) -> int: ifnot grid: return0 rowsn = len(grid) colsn = len(grid[0]) uf = UF(rowsn*colsn) # 统计'1'的个数: cnt = 0 for i in range(rowsn): for j in range(colsn): if grid[i][j] == '1': cnt += 1 uf.count = cnt for i in range(rowsn): for j in range(colsn): if grid[i][j] == '1': # 标记探索过的网格 grid[i][j] = '2' # 只需向右下方查看合并 for di, dj in ((0,1), (1,0)): ii = i + di jj = j + dj if0 <= ii < rowsn and0 <= jj < colsn and grid[ii][jj] == '1': uf.union(i*colsn+j, ii*colsn+jj) return uf.count