In a N x N grid
composed of 1 x 1 squares, each 1 x 1 square consists of a /
, \
, or blank space. These characters divide the square into contiguous regions.
(Note that backslash characters are escaped, so a \
is represented as "\\"
.)
Return the number of regions.
Example 1:
Input: [ " /", "/ " ] Output: 2 Explanation: The 2x2 grid is as follows:
Example 2:
Input: [ " /", " " ] Output: 1 Explanation: The 2x2 grid is as follows:
Example 3:
Input: [ "\\/", "/\\" ] Output: 4 Explanation: (Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.) The 2x2 grid is as follows:
Example 4:
Input: [ "/\\", "\\/" ] Output: 5 Explanation: (Recall that because \ characters are escaped, "/\\" refers to /\, and "\\/" refers to \/.) The 2x2 grid is as follows:
Example 5:
Input: [ "//", "/ " ] Output: 3 Explanation: The 2x2 grid is as follows:
Note:
1 <= grid.length == grid[0].length <= 30
grid[i][j]
is either'/'
,'\'
, or' '
.
--------------------------------------------------
The largest difficulty for this problem is transforming into find merge set:
up 0, right 1, down 2, left 3
class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
f = {}
def find(x):
if (x not in f):
f[x] = x
elif(f[x] != x):
f[x] = find(f[x])
return f[x]
def merge(x,y):
rx,ry = find(x),find(y)
f[rx] = ry
rows, cols = len(grid), len(grid[0]) if grid else 0
for i in range(rows):
for j in range(cols):
cur = (i * cols + j) * 4
up, left = ((i - 1) * cols + j) * 4, (i * cols + j - 1) * 4
cl, cr, cd = cur + 3, cur + 1, cur + 2
lr,ud = left + 1, up + 2
if (grid[i][j] == '/'):
merge(cur, cl)
merge(cr, cd)
elif (grid[i][j] == '\\'):
merge(cur, cr)
merge(cl, cd)
else:
merge(cur, cr)
merge(cl, cd)
merge(cur, cl)
if (i >= 1):
merge(cur,ud)
if (j >= 1):
merge(cl,lr)
res = 0
for i in range(rows):
for j in range(cols):
cur = (i * cols + j) * 4
for dx in range(4):
if (cur+dx == find(cur+dx)):
res += 1
return res