LeetCode 261 [Graph Valid Tree]

原题

给出 n 个节点,标号分别从 0 到 n - 1 并且给出一个 无向 边的列表 (给出每条边的两个顶点), 写一个函数去判断这张`无向`图是否是一棵树

样例
给出n = 5 并且 edges = [[0, 1], [0, 2], [0, 3], [1, 4]], 返回 true.
给出n = 5 并且 edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], 返回 false.

解题思路

  • 判断输入的边,是否能构成树看两点:
  • 是否有环,有环则不是树
  • 是否所有点最终都相连,有不相连则不是树
  • 集合合并问题,使用并查集
  • 如果合并的时候发现两个点的father一样,则有环
  • 最终统计father的个数,超过一个说明没有全部相连

完整代码

class UnionFind:
    def __init__(self, n):
        self.father = {}
        for i in range(n):
            self.father[i] = i 
  
    def compressed_find(self, x):
        parent = self.father[x]
        while parent != self.father[parent]:
            parent = self.father[parent]

        temp = -1;
        fa = self.father[x]
        while fa != self.father[fa]:
            temp = self.father[fa]
            self.father[fa] = parent
            fa = temp

        return parent

        
    def union(self, x, y):
            fa_x = self.compressed_find(x)
            fa_y = self.compressed_find(y)
            if fa_x != fa_y:
                self.father[fa_x] = fa_y

class Solution:
    # @param {int} n an integer
    # @param {int[][]} edges a list of undirected edges
    # @return {boolean} true if it's a valid tree, or false
    def validTree(self, n, edges):
        # Write your code here
        if len(edges) != n - 1:
            return False
            
        uf = UnionFind(n)
        
        for edge in edges:
            pointA, pointB = edge[0], edge[1]
            fpointA = uf.compressed_find(pointA)
            fpointB = uf.compressed_find(pointB)
            if fpointA == fpointB:
                return False
            else:
                uf.union(pointA, pointB)
                
        return True
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • 1 序 2016年6月25日夜,帝都,天下着大雨,拖着行李箱和同学在校门口照了最后一张合照,搬离寝室打车去了提前租...
    RichardJieChen阅读 10,606评论 0 12
  • 树形动态规划,顾名思义就是树+DP,先分别回顾一下基本内容吧:动态规划:问题可以分解成若干相互联系的阶段,在每一个...
    Mr_chong阅读 5,366评论 0 2
  • 用语音来整理思路,会是一个怎样的流程呢?今天做一下尝试。 如何避免认知错位中的以局部代替整体呢? 01 不要相信最...
    Helexy22阅读 2,773评论 0 0