题目描述:在由 1 x 1 方格组成的 N x N 网格 grid 中,每个 1 x 1 方块由 /、\ 或空格构成。这些字符会将方块划分为一些共边的区域。
(请注意,反斜杠字符是转义的,因此 \ 用 “\” 表示。)。
返回区域的数目。
解题思路:每个一个网格分成上下左右四个三角形,如果是左斜杠就连接0、3和1、2三角形,如果是反斜杠,就连接0、1和2、3三角形,如果是空格就连接四个三角形,另外还要连接网格之间的三角形,进行左右和上下的连接,代码如下:
class UnionFind():
def __init__(self, n):
self.count = n
self.father = list(range(n))
def find(self, x):
root = x
while(root != self.father[root]):
root = self.father[root]
while(x != root):
origin_r = self.father[x]
self.father[x] = root
x = origin_r
return root
def union(self, x, y):
root_x, root_y = self.find(x), self.find(y)
if root_x != root_y:
self.count -= 1
self.father[root_x] = self.father[root_y]
def getCount(self):
return self.count
class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
n = len(grid)
uf = UnionFind(4*n*n)
# father = list(range(4*n*n))
# count = 4*n*n
# def find(x):
# def union(x, y):
# root_x, root_y = find(x), find(y)
# if root_x != root_y:
# count -= 1
# father[root_x] = father[root_y]
for i in range(n):
for j in range(n):
index = 4*(i*n+j)
if grid[i][j] == '/':
uf.union(index, index+3)
uf.union(index+1, index+2)
elif grid[i][j] == '\\':
uf.union(index, index+1)
uf.union(index+2, index+3)
else:
uf.union(index, index+1)
uf.union(index+1, index+2)
uf.union(index+2, index+3)
if j+1 < n:
uf.union(index+1, 4*(i*n+j+1)+3)
if i+1 < n:
uf.union(index+2, 4*((i+1)*n + j))
return uf.getCount()