![](https://img-blog.csdnimg.cn/20201014180756780.png?x-oss-process=image/resize,m_fixed,h_64,w_64)
并查集
996冲冲冲
这个作者很懒,什么都没留下…
展开
-
LC1319. 连通网络的操作次数
解题思路,如果边的个数少于顶点个数减一,那么肯定无法全部连通 如果大于等于,一定可以全部连通。此时我们找连通分量的个数,其实把这些连通分量整体看作节点的话 也需要连通分量个数减一的边将它们连通,因为一定可以连通,所以返回连通分量减一就是答案 def makeConnected(self, n, connections): """ :type n: int :type connections: List[List[int]] :rtype: in原创 2022-05-17 21:50:54 · 76 阅读 · 0 评论 -
LC959. 由斜杠划分区域
并查集找环的个数 def regionsBySlashes(self, grid): """ :type grid: List[str] :rtype: int """ n = len(grid) m = n+1 l = (n + 1) * (n + 1) #正方形节点数,画一下图就明白了 parent = list(range(l+原创 2022-05-16 21:51:49 · 46 阅读 · 0 评论 -
LC947. 移除最多的同行或同列石头
并查集,看图中有多少连通分量。删除最多可以是每个连通分量里只剩一个石子。所以总的减去连通分量的个数就是答案 class Solution(object): def removeStones(self, stones): """ :type stones: List[List[int]] :rtype: int """ n = len(stones) self.count = n paren原创 2022-05-16 16:45:49 · 131 阅读 · 0 评论 -
LC990. 等式方程的可满足性
注意并查集的应用,这题的思路是把等于的两个字母连通,又因为并查集的传递性,和等于的传递性相同。最终就是相等的和由于传递性相等的被放在同一个集合。这样分成了多个连通区域。 之后,不等的必须在不同的区域才算正确,因为同一个区域的必须保证相等。 所以遍历一遍判断不等的里有没有在同一区域的,如果有返回False。没有返回True def equationsPossible(self, equations): """ :type equations: List[str]原创 2022-05-12 22:06:13 · 57 阅读 · 0 评论 -
LC684. 冗余连接
并查集查找无向图中的环 def findRedundantConnection(self, edges): """ :type edges: List[List[int]] :rtype: List[int] """ n = len(edges) parent = list(range(n+1)) def find(x): if parent[x] != x:原创 2022-05-12 21:06:29 · 63 阅读 · 0 评论 -
LC685. 冗余连接 II
注意这题一共有三种情况构不成树,一是有环,二是有入度为2的节点,三是又有环又有出度为2的节点 class UnionSet: def __init__(self,n): self.ancestor = list(range(n)) def find(self,x): if x != self.ancestor[x]: self.ancestor[x] = self.find(self.ancestor[x]) retur原创 2022-05-12 20:57:34 · 78 阅读 · 0 评论