为ae做片段视频项目配置专属AI模型并控制成本
2026/5/13 0:00:07
给定一个 m x n 的二维网格,最初所有位置都是水。现在给定一个数组 positions,表示添加陆地的位置。返回每次添加陆地后岛屿的数量。
示例:
输入:m = 3,n = 3,positions = [[0,0],[0,1],[1,2],[2,1]]
输出:[1,1,2,2]
思路:
复杂度分析:
class UnionFind: def __init__(self, n): self.parent = list(range(n)) self.rank = [0] * n self.count = 0 def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, x, y): px, py = self.find(x), self.find(y) if px == py: return False if self.rank[px] < self.rank[py]: px, py = py, px self.parent[py] = px if self.rank[px] == self.rank[py]: self.rank[px] += 1 self.count -= 1 return True def num_islands2(m, n, positions): uf = UnionFind(m * n) grid = [[False] * n for _ in range(m)] result = [] for pos in positions: i, j = pos[0], pos[1] index = i * n + j if not grid[i][j]: grid[i][j] = True uf.count += 1 if i > 0 and grid[i-1][j]: uf.union(index, (i-1) * n + j) if i < m - 1 and grid[i+1][j]: uf.union(index, (i+1) * n + j) if j > 0 and grid[i][j-1]: uf.union(index, i * n + j - 1) if j < n - 1 and grid[i][j+1]: uf.union(index, i * n + j + 1) result.append(uf.count) return result # 测试 def test_num_islands2(): m, n = 3, 3 positions = [[0,0], [0,1], [1,2], [2,1]] print(num_islands2(m, n, positions)) # 输出:[1, 1, 2, 2] if __name__ == "__main__": test_num_islands2()岛屿数量II是并查集的典型应用,每次添加陆地后更新岛屿数量。