# leetcode —— 959. 由斜槓劃分區域

（請注意，反斜槓字符是轉義的，因此 \ 用 “\” 表示。）。

————————————

``````class Solution:
def __init__(self):
self.ans = 0
def regionsBySlashes(self, grid: List[str]) -> int:
length = len(grid)
# 構造進行深度遍歷的小方格矩陣
grids = [[0 for _ in range(length*3)] for _ in range(length*3)]
# 基於給定的grid修改小方格中的值
# 在出現斜邊的位置將其值標記爲1
for i in range(length):
for j in range(length):
if grid[i][j] == '\\':
grids[i*3][j*3] = 1
grids[i*3+1][j*3+1] = 1
grids[i*3+2][j*3+2] = 1
if grid[i][j] == '/':
grids[i*3][j*3+2] = 1
grids[i*3+1][j*3+1] = 1
grids[i*3+2][j*3] = 1

# 深度優先遍歷遞歸函數
def dfs(grids,i,j):
grids[i][j] = 1
for x,y in [[i-1,j],[i+1,j],[i,j-1],[i,j+1]]:
if x<0 or x==3*length or y<0 or y==3*length or grids[x][y] == 1:
continue
dfs(grids,x,y)

for i in range(length*3):
for j in range(length*3):
if grids[i][j] == 0:
self.ans += 1
dfs(grids,i,j)
return self.ans
``````
``````class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
N = len(grid)
parent = [i for i in range(4 * N * N)] # 開始的時候每個節點的幫主都是自己
def find(parent, x): # 尋找每個節點的幫主
if parent[x] == x:
return parent[x]
return find(parent, parent[x])

def union(parent, x, y): # 兩個人相遇， 那麼各自去找教主，教主對決
x_root = find(parent, x)
y_root = find(parent, y)
if x_root != y_root: # 教主不同
parent[x_root] = y_root # 對決贏的成爲新教主

def union_find(grid):
for r, row in enumerate(grid):
for c, val in enumerate(row):
top = 4 * (r * N + c)
# 將一個方格內的連通單元進行拼接
if val in ['/', ' ']:
union(parent, top + 0, top + 1)
union(parent, top + 2, top + 3)
if val in ['\\', ' ']:
union(parent, top + 0, top + 2)
union(parent, top + 1, top + 3)
# 將單元件的連通單元進行拼接
if r + 1 < N:
union(parent, top + 3, top + (4 * N) + 0)
if r - 1 >= 0:# 這部分其實是多於的
union(parent, top + 0, top - (4 * N) + 3)
if c + 1 < N:
union(parent, top + 2, top + 4 + 1)
if c - 1 >= 0: # 這部分其實也是多於的
union(parent, top + 1, top - 4 + 2)

return sum(parent[x] == x for x in range(4 * N * N ))
return union_find(grid)
``````