- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 46 lines of Python from the credited upstream file swim-in-rising-water.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class UnionFind(object):5 def __init__(self, n):6 self.set = range(n)7 8 def find_set(self, x):9 if self.set[x] != x:10 self.set[x] = self.find_set(self.set[x]) 11 return self.set[x]12 13 def union_set(self, x, y):14 x_root, y_root = map(self.find_set, (x, y))15 if x_root == y_root:16 return False17 self.set[min(x_root, y_root)] = max(x_root, y_root)18 return True19 20 21class Solution(object):22 def swimInWater(self, grid):23 """24 :type grid: List[List[int]]25 :rtype: int26 """27 n = len(grid)28 positions = [None] * (n**2)29 for i in xrange(n):30 for j in xrange(n):31 positions[grid[i][j]] = (i, j)32 directions = ((-1, 0), (1, 0), (0, -1), (0, 1))33 34 union_find = UnionFind(n**2)35 for elevation in xrange(n**2):36 i, j = positions[elevation]37 for direction in directions:38 x, y = i+direction[0], j+direction[1]39 if 0 <= x < n and 0 <= y < n and grid[x][y] <= elevation:40 union_find.union_set(i*n+j, x*n+y)41 if union_find.find_set(0) == union_find.find_set(n**2-1):42 return elevation43 return n**2-144 45 46