Python、C++、JavaScript、SQL、TypeScript の多様な LeetCode ソリューションを探索してください。面接の準備、学習、複数のプログラミング言語でのコードの練習に最適です。 Github リポジトリ リンク
You are given an empty 2D binary grid グリッド
of size xn
. The grid represents a map where 0
‘s represent water and 1
‘s represent land. Initially, all the cells of グリッド
are water cells (i.e., all the cells are 0
‘s).
We may perform an add land operation which turns the water at position into a land. You are given an array positions
どこ positions[i] = [ri, ci]
is the position (r i , c i )
at which we should operate the 私は
operation.
戻る an array of integers 答え
どこ 答え[i]
is the number of islands after turning the cell (r i , c i )
into a land.
アン 島 は水に囲まれており、隣接する土地を水平または垂直に接続することによって形成されます。グリッドの 4 つの端すべてが水に囲まれていると考えることができます。
例 1:
入力: m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]] 出力: [1,1,2,3] 説明: Initially, the 2d grid is filled with water. - Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land. We have 1 island. - Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. We still have 1 island. - Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. We have 2 islands. - Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. We have 3 islands.
例 2:
入力: m = 1, n = 1, positions = [[0,0]] 出力: [1]
制約:
1 <= m, n, positions.length <= 104
1 <= m * n <= 104
positions[i].length == 2
0 <= ri < m
0 <= ci < n
フォローアップ: Could you solve it in time complexity O(k log(mn))
, where k == positions.length
?
パイソン
# time complexity: O(m*n)
# space complexity: O(m*n)
from typing import List
class Solution:
class UnionFind:
def __init__(self, size):
self.rep = [i for i in range(size)]
self.rank = [0] * size
self.count = 0
def find(self, node):
if node != self.rep[node]:
self.rep[node] = self.find(self.rep[node])
return self.rep[node]
def union(self, node1, node2):
rep1 = self.find(node1)
rep2 = self.find(node2)
if rep1 != rep2:
if self.rank[rep1] > self.rank[rep2]:
self.rep[rep2] = rep1
elif self.rank[rep2] < self.rank[rep1]:
self.rep[rep1] = rep2
else:
self.rep[rep2] = rep1
self.rank[rep1] += 1
self.count -= 1
def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]:
uf = self.UnionFind(m * n)
res = []
land_map = set()
for row, col in positions:
if (row, col) in land_map:
res.append(uf.count)
continue
land_map.add((row, col))
uf.count += 1
for i, j in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
r, c = row + i, col + j
if r < 0 or c < 0 or r >= m or c >= n:
continue
if (r, c) in land_map:
uf.union(row * n + col, r * n + c)
res.append(uf.count)
return res
m = 3
n = 3
positions = [[0, 0], [0, 1], [1, 2], [2, 1]]
print(Solution().numIslands2(m, n, positions))