1# Runtime: 124 ms (Top 90.60%) | Memory: 14.5 MB (Top 61.93%)2class Solution:3def regionsBySlashes(self, grid: List[str]) -> int:4n = len(grid)5dots = n + 16par = [0] * (dots * dots)7rank = [0] * (dots * dots)8self.count = 1910def find(x):11if par[x] == x:12return x13temp = find(par[x])14par[x] = temp15return temp1617def union(x, y):18lx = find(x)19ly = find(y)20if lx != ly:21if rank[lx] > rank[ly]:22par[ly] = lx23elif rank[lx] < rank[ly]:24par[lx] = ly25else:26par[lx] = ly27rank[ly] += 128else:29self.count += 13031# -------------------------------------------#32for i in range(len(par)):33par[i] = i34rank[i] = 135for i in range(dots):36for j in range(dots):37if i == 0 or j == 0 or i == dots - 1 or j == dots - 1:38cellno = i * dots + j39if cellno != 0:40union(0, cellno)41for i in range(len(grid)):42ch = grid[i]43for j in range(len(ch)):44if ch[j] == "/":45cellno1 = i * dots + j + 146cellno2 = (i + 1) * dots + j4748union(cellno1, cellno2)49elif ch[j] == "\\":50cellno1 = i * dots + j51cellno2 = (i + 1) * dots + j + 152union(cellno1, cellno2)53return self.count