125 日 , 2021 21:07:01
leetcode打卡

959. 由斜杠划分区域

今天的题,依旧并查集

更多的例子

做法

计算并查集连通分量,借leetcode大佬的图

下面是代码(py)

class Solution:
    def regionsBySlashes(self, grid: List[str]) -> int:
        N=len(grid)
        parent=[i for i in range(4*N*N)]
        def find(node):#递归寻找根节点
            if parent[node] != node:
                parent[node] = find(parent[node])
            return parent[node]
        def union(a,b):#链接节点
            root_a,root_b = find(a),find(b)
            if root_a != root_b:
                parent[root_a] = root_b
        for r in range(N):
            for c in range(N):
                base = 4 * (r * N + c)#当前第一个的编号
                char=grid[r][c]
                if char == '\\':
                    union(base+0,base+3)
                    union(base+1,base+2)
                elif char=='/':
                    union(base+0,base+1)
                    union(base+2,base+3)
                else:
                    union(base+0,base+1)
                    union(base+2,base+3)
                    union(base+0,base+2)
                if c < N-1:
                    union(base+2,base+4)
                if r < N-1:
                    union(base+3,base+4*N+1)
        return sum(parent[i] == i for i in range(4*N*N))
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!