|
| 1 | +import copy |
| 2 | + |
| 3 | +import solution |
| 4 | +from typing import * |
| 5 | + |
| 6 | + |
| 7 | +class Solution(solution.Solution): |
| 8 | + def solve(self, test_input=None): |
| 9 | + return self.largestIsland(test_input) |
| 10 | + |
| 11 | + def largestIsland(self, grid: List[List[int]]) -> int: |
| 12 | + DIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)] |
| 13 | + def point_to_idx(x, y): |
| 14 | + return x * n + y |
| 15 | + |
| 16 | + |
| 17 | + |
| 18 | + n = len(grid) |
| 19 | + uf = UnionFind(n * n) |
| 20 | + for i, row in enumerate(grid): |
| 21 | + for j, val in enumerate(row): |
| 22 | + if val == 1: |
| 23 | + p = point_to_idx(i, j) |
| 24 | + for dx, dy in DIRS: |
| 25 | + if 0 <= (nx := i + dx) < n and 0 <= (ny := j + dy) < n and grid[nx][ny] == 1: |
| 26 | + uf.union(p, point_to_idx(nx, ny)) |
| 27 | + ans = max(uf.count) |
| 28 | + for i, row in enumerate(grid): |
| 29 | + for j, val in enumerate(row): |
| 30 | + if val == 0: |
| 31 | + tot = 1 |
| 32 | + explored = set() |
| 33 | + for dx, dy in DIRS: |
| 34 | + if 0 <= (nx := i + dx) < n and 0 <= (ny := j + dy) < n and grid[nx][ny] == 1: |
| 35 | + root = uf.find(point_to_idx(nx, ny)) |
| 36 | + if root in explored: |
| 37 | + continue |
| 38 | + explored.add(root) |
| 39 | + tot += uf.count[root] |
| 40 | + ans = max(ans, tot) |
| 41 | + |
| 42 | + return ans |
| 43 | + |
| 44 | +class UnionFind: |
| 45 | + def __init__(self, size): |
| 46 | + self.parent = list(range(size)) |
| 47 | + self.rank = [1] * size |
| 48 | + self.count = [1] * size |
| 49 | + self.size = size |
| 50 | + self.cc = size |
| 51 | + |
| 52 | + def find(self, x): |
| 53 | + while self.parent[x] != x: |
| 54 | + self.parent[x] = self.parent[self.parent[x]] # 路径压缩 |
| 55 | + x = self.parent[x] |
| 56 | + return x |
| 57 | + |
| 58 | + def union(self, x, y): |
| 59 | + root_x = self.find(x) |
| 60 | + root_y = self.find(y) |
| 61 | + |
| 62 | + if root_x == root_y: |
| 63 | + return False # 已经在同一集合 |
| 64 | + |
| 65 | + # 按秩合并 |
| 66 | + if self.rank[root_x] > self.rank[root_y]: |
| 67 | + self.parent[root_y] = root_x |
| 68 | + self.count[root_x] += self.count[root_y] |
| 69 | + else: |
| 70 | + self.parent[root_x] = root_y |
| 71 | + if self.rank[root_x] == self.rank[root_y]: |
| 72 | + self.rank[root_y] += 1 |
| 73 | + self.count[root_y] += self.count[root_x] |
| 74 | + self.cc -= 1 |
| 75 | + return True |
| 76 | + |
| 77 | + def is_connected(self, x, y): |
| 78 | + return self.find(x) == self.find(y) |
0 commit comments