- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 76 lines of Python from the credited upstream file detect-cycles-in-2d-grid.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 self.count = n8 9 def find_set(self, x):10 if self.set[x] != x:11 self.set[x] = self.find_set(self.set[x]) 12 return self.set[x]13 14 def union_set(self, x, y):15 x_root, y_root = map(self.find_set, (x, y))16 if x_root != y_root:17 self.set[min(x_root, y_root)] = max(x_root, y_root)18 self.count -= 119 20 21class Solution(object):22 def containsCycle(self, grid):23 """24 :type grid: List[List[str]]25 :rtype: bool26 """27 def index(n, i, j):28 return i*n + j29 30 union_find = UnionFind(len(grid)*len(grid[0]))31 for i in xrange(len(grid)):32 for j in xrange(len(grid[0])):33 if i and j and grid[i][j] == grid[i-1][j] == grid[i][j-1] and \34 union_find.find_set(index(len(grid[0]), i-1, j)) == \35 union_find.find_set(index(len(grid[0]), i, j-1)):36 return True37 if i and grid[i][j] == grid[i-1][j]:38 union_find.union_set(index(len(grid[0]), i-1, j),39 index(len(grid[0]),i, j))40 if j and grid[i][j] == grid[i][j-1]:41 union_find.union_set(index(len(grid[0]), i, j-1),42 index(len(grid[0]), i, j))43 return False44 45 464748class Solution2(object):49 def containsCycle(self, grid):50 """51 :type grid: List[List[str]]52 :rtype: bool53 """54 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]55 for i in xrange(len(grid)):56 for j in xrange(len(grid[0])):57 if not grid[i][j]:58 continue59 val = grid[i][j]60 q = [(i, j)]61 while q:62 new_q = []63 for r, c in q:64 if not grid[r][c]:65 return True66 grid[r][c] = 067 for dr, dc in directions:68 nr, nc = r+dr, c+dc69 if not (0 <= nr < len(grid) and70 0 <= nc < len(grid[0]) and71 grid[nr][nc] == val):72 continue73 new_q.append((nr, nc))74 q = new_q75 return False76