【Leetcode】959. Regions Cut By Slashes 959. 由斜杠划分区域

【Leetcode】959. Regions Cut By Slashes 959. 由斜杠划分区域_第1张图片
【Leetcode】959. Regions Cut By Slashes 959. 由斜杠划分区域_第2张图片
【Leetcode】959. Regions Cut By Slashes 959. 由斜杠划分区域_第3张图片
【Leetcode】959. Regions Cut By Slashes 959. 由斜杠划分区域_第4张图片

解法

就是并查集,把每个1x1的方格再划分成4个格子,比如这样:
【Leetcode】959. Regions Cut By Slashes 959. 由斜杠划分区域_第5张图片

class Solution:
    def regionsBySlashes(self, grid: List[str]) -> int:
        n = len(grid)
        # print(n)
        num = n*n
        f = list(range(4*num))
        def find(x):
            r = x
            # print(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):
            # print(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

你可能感兴趣的:(Leetcode)