2
def __init__(self, m, n):3
self.n, self.loc_id, c_id = n, dict(), 04
self.col_set = [set() for _ in range(m * n)]5
for i in range(m): # Assign id for each location (i ,j)7
self.loc_id[(i, j)] = c_id8
self.col_set[c_id].add(j)10
self.p = [i for i in range(m * n)] # Initialize parents array `p`14
self.p[i] = self.find(self.p[i])17
def union(self, i, j):18
pi, pj = self.find(i), self.find(j)20
self.p[pj] = pi # Update `pi`22
self.col_set[pi] | self.col_set[pj]23
) # Take union of two sets (union all occupied columns)25
len(self.col_set[pi]) == self.n26
) # if length of col_set[pi] == self.n, meaning this piece occupied all columns from 1 to `col` inclusive, meaning we are blocked30
def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:31
uf, visited = UF(row, col), set()32
for i, (x, y) in enumerate(cells):45
_x, _y = x + dx, y + dy # Check if neighbor is flooded46
if 0 <= _x < row and 0 <= _y < col and (_x, _y) in visited:47
id1, id2 = uf.loc_id[(_x, _y)], uf.loc_id[(x, y)]48
if uf.union(id1, id2):49
return i # Union two flooded piece and return index if union return True