1. 程式人生 > >959. Regions Cut By Slashes

959. Regions Cut By Slashes

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. 1 <= grid.length == grid[0].length <= 30
  2. grid[i][j] is either '/''\', or ' '.

思路:union find

把每個小正方形box沿著2個對角線拆成上下左右4部分(每個小部分都是一個三角形),假設矩陣大小N*M,現在就有4*N*M個小部分,

然後把所有的小部分union起來就好了。有2種union情況

1. 相鄰的的小正方形box

2. 一個小正方形內4個三角形之間:union方式取決於這個小正方形的位置上是什麼字元,如果是空字元,就把4個小三角形都union,如果是"/",就把左邊和上面的三角形union,右邊和下邊的三角形union;如果是"\",就把左邊和下邊的三角形union,上邊和右邊的三角形union

 

ref:https://leetcode.com/problems/regions-cut-by-slashes/solution/

 

class Solution(object):
    def regionsBySlashes(self, grid):
        """
        :type grid: List[str]
        :rtype: int
        """
        n,m=len(grid),len(grid[0])
        N = 4*n*m
        fa = list(range(N))
        
        def find(i):
            while i!=fa[i]: i=fa[i]
            return i
        def union(i,j):
            fi,fj=find(i),find(j)
            fa[fi]=fj
            
        # union neighbor box
        for i in range(n):
            for j in range(m):
                cur=m*i+j
                if j!=m-1:
                    right=cur+1
                    union(4*cur+3, 4*right+2)
                if i!=n-1:
                    down=cur+m
                    union(4*cur+1, 4*down)
        
        # union inside box
        for i in range(n):
            for j in range(m):
                cur=m*i+j
                if grid[i][j]==' ':
                    union(4*cur, 4*cur+1)
                    union(4*cur, 4*cur+2)
                    union(4*cur, 4*cur+3)
                elif grid[i][j]=='/':
                    union(4*cur, 4*cur+2)
                    union(4*cur+1, 4*cur+3)
                else:
                    union(4*cur, 4*cur+3)
                    union(4*cur+1, 4*cur+2)
        
        return len(set([find(i) for i in range(N)]))
    
    
s=Solution()
print(s.regionsBySlashes([
  " /",
  "/ "
]))
print(s.regionsBySlashes([
  " /",
  "  "
]))
print(s.regionsBySlashes([
  "\\/",
  "/\\"
]))
print(s.regionsBySlashes([
  "/\\",
  "\\/"
]))
print(s.regionsBySlashes([
  "//",
  "/ "
]))