解法
就是并查集,把每个1x1的方格再划分成4个格子,比如这样:
class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
n = len(grid)
num = n*n
f = list(range(4*num))
def find(x):
r = x
while f[r]!=r:
r = f[r]
while f[x]!=r:
tmp = f[x]
f[x] = r
x = tmp
return r
def toId(i,j,d):
return d*num+i*n+j
def toNode(x):
return x%n, x%num//n, x//num
self.total = 4*num
def join(x,y):
rx,ry = find(x), find(y)
if rx!=ry:
self.total -= 1
f[rx]=ry
for i in range(n):
for j in range(n):
if grid[i][j] ==" ":
join(toId(i,j,0),toId(i,j,1))
join(toId(i,j,2),toId(i,j,1))
join(toId(i,j,2),toId(i,j,3))
elif grid[i][j]=='/':
join(toId(i,j,0),toId(i,j,3))
join(toId(i,j,2),toId(i,j,1))
elif grid[i][j]=='\\':
join(toId(i,j,0),toId(i,j,1))
join(toId(i,j,2),toId(i,j,3))
if i>0:
join(toId(i,j,0), toId(i-1,j,2))
if i+1<n:
join(toId(i,j,2), toId(i+1,j,0))
if j>0:
join(toId(i,j,3), toId(i,j-1,1))
if j+1<n:
join(toId(i,j,1), toId(i,j+1,3))
return self.total