2
def largestIsland(self, grid: List[List[int]]) -> int:3
m, n = len(grid), len(grid[0])4
# parent array to keey track5
parent = list(range(m * n))6
# rank array used for union by rank and size calculation7
rank = [1 for _ in range(m * n)]9
# standard DSU find function12
parent[x] = parent[parent[x]]16
# standard DSU union by rank function18
parX, parY = find(x), find(y)21
if rank[parX] >= rank[parY]:22
rank[parX] += rank[parY]25
rank[parY] += rank[parX]28
# Step 1: join the land30
# for each island we perform union operation31
for i, row in enumerate(grid):32
for j, val in enumerate(row):34
# important condition: if we have a water body, we set its rank to 0 (will be used in the next step)39
# performing union of land bodies40
for x, y in [(i - 1, j), (i + 1, j), (i, j + 1), (i, j - 1)]:41
# outside of grid check42
if not (0 <= x < m and 0 <= y < n):46
union(i * m + j, x * m + y)48
# Step 2: convert a water body (if present)50
# the minimum final ans will always be the size of the largest land present52
for i, row in enumerate(grid):53
for j, val in enumerate(row):55
# we dont need to do anything if we encounter a land63
for x, y in [(i - 1, j), (i + 1, j), (i, j + 1), (i, j - 1)]:64
# outside of grid check65
if not (0 <= x < m and 0 <= y < n):68
# checking unique neighbours by adding the parent to the set69
# here we dont care if the neighbour is water as its rank is 0 so it contributes nothing71
neighbours.add(find(idx))73
# Once we have all unique neighbours, just add their ranks74
for idx in neighbours:77
# res + 1 because we convert the current cell (i,j) to land too78
ans = max(ans, res + 1)