959. 由斜杠划分区域

题目描述:在由 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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值