Graph Valid Tree

要点:本身题不难,关键是这题涉及几道关联题目,要清楚之间的差别和关联才能解类似题:isTree就比isCycle多了检查连通性,所以这一系列题从结构上分以下三部分

  • given a graph or edges?有可能给点的编号,然后只给edges,这个最适合用union-find。如果用dfs,那么要先转化成adjacent list表示。这样如果直接给的连通关系的graph,那么dfs就比较直接了
  • isCycle:directed or undirected:dfs过程中,如果不需要连通,那么要dfs外加一层loop。directed要加一个recStack(一般是个set,因为要判断是不是已经在里面):visited但是不在stack里,说明是从其他通路曾经访问的,可以早return,但不表示false。而undirected只需要visited,需要检查的只有visited的neighbor不是parent,那么return false。
  • isTree:directed or undirected:
    • dfs,undirected:由于需要连通的特性,undirected比较简单,不需要外层loop,直接一遍dfs后看还有没有没连通的。
    • dfs,directed:先要找到root(也就是过一遍所有的结点,找到唯一的无入度的点)。然后从这个结点开始做和undirected一样的dfs,看有没有环,以及最后是否遍历了。注意这里比较tricky,因为如果一个结点有2+个入度,那么一定不是树,而只有这种情况才会出现directed graph无环的特殊情况。
    • 而如果用union-find,undirected/directed都类似,就是看最后是不是只有一个root

https://repl.it/Ci3M/1

  1. # Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
  2. # For example:
  3. # Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.
  4. # Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.
  5. # Hint:
  6. # Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree?
  7. # According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
  8. # Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
  9. # Hide Company Tags Google Facebook Zenefits
  10. # Hide Tags Depth-first Search Breadth-first Search Graph Union Find
  11. # Hide Similar Problems (M) Course Schedule (M) Number of Connected Components in an Undirected Graph
  12. class Solution(object):
  13. def validTree(self, n, edges):
  14. """
  15. :type n: int
  16. :type edges: List[List[int]]
  17. :rtype: bool
  18. """
  19. parents = range(n)
  20. self.count = n
  21. def find(x):
  22. if parents[x]!=x:
  23. parents[x]=find(parents[x])
  24. return parents[x]
  25. def union(x,y):
  26. x,y = find(x),find(y)
  27. if x!=y:
  28. parents[x]=y
  29. self.count-=1
  30. return True
  31. return False
  32. for e in edges:
  33. if not union(e[0], e[1]):
  34. return False
  35. return self.count==1
  36. sol = Solution()
  37. assert sol.validTree(5, [[0, 1], [0, 2], [0, 3], [1, 4]])==True
  38. assert sol.validTree(5, [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]])==False

边工作边刷题:70天一遍leetcode: day 78的更多相关文章

  1. 边工作边刷题:70天一遍leetcode: day 89

    Word Break I/II 现在看都是小case题了,一遍过了.注意这题不是np complete,dp解的time complexity可以是O(n^2) or O(nm) (取决于inner ...

  2. 边工作边刷题:70天一遍leetcode: day 77

    Paint House I/II 要点:这题要区分房子编号i和颜色编号k:目标是某个颜色,所以min的list是上一个房子编号中所有其他颜色+当前颜色的cost https://repl.it/Chw ...

  3. 边工作边刷题:70天一遍leetcode: day 85-3

    Zigzag Iterator 要点: 实际不是zigzag而是纵向访问 这题可以扩展到k个list,也可以扩展到只给iterator而不给list.结构上没什么区别,iterator的hasNext ...

  4. 边工作边刷题:70天一遍leetcode: day 101

    dp/recursion的方式和是不是game无关,和game本身的规则有关:flip game不累加值,只需要一个boolean就可以.coin in a line II是从一个方向上选取,所以1d ...

  5. 边工作边刷题:70天一遍leetcode: day 1

    (今日完成:Two Sum, Add Two Numbers, Longest Substring Without Repeating Characters, Median of Two Sorted ...

  6. 边工作边刷题:70天一遍leetcode: day 70

    Design Phone Directory 要点:坑爹的一题,扩展的话类似LRU,但是本题的accept解直接一个set搞定 https://repl.it/Cu0j # Design a Phon ...

  7. 边工作边刷题:70天一遍leetcode: day 71-3

    Two Sum I/II/III 要点:都是简单题,III就要注意如果value-num==num的情况,所以要count,并且count>1 https://repl.it/CrZG 错误点: ...

  8. 边工作边刷题:70天一遍leetcode: day 71-2

    One Edit Distance 要点:有两种解法要考虑:已知长度和未知长度(比如只给个iterator) 已知长度:最好不要用if/else在最外面分情况,而是loop在外,用err记录misma ...

  9. 边工作边刷题:70天一遍leetcode: day 71-1

    Longest Substring with At Most K Distinct Characters 要点:要搞清楚At Most Two Distinct和Longest Substring W ...

随机推荐

  1. spring aop advice

    1.前置通知(BeforeAdvice): import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAd ...

  2. velocity merge作为工具类从web上下文和jar加载模板的两种常见情形

    很多时候,处于各种便利性或折衷或者通用性亦或是限制的原因,会借助于模板生成结果,在此介绍两种使用velocity merge的情形,第一种是和spring mvc一样,将模板放在velocityCon ...

  3. SharePoint 2013 新功能探索 之 列表等级设置

    一.列表等级及赞功能 ,在SharePoint 2010 中,对列表的等级设定,需要一定时间才能看到,现在可以实时同步,评分人数也能显示出来 等级分为两类 赞和星级评定   

  4. SharePoint 2013 的HTML5特性之响应式布局

    今天偶然看到一本书<Pro SharePoint 2013 Branding and Responsive Web Development>,看到SharePoint 2013基于HTML ...

  5. redis实现主从复制-单机测试

    一.redis实现主从复制-单机测试1.安装redis tar -zxvf redis-2.8.4.tar.gzcd redis-2.8.4make && make install2. ...

  6. Android子线程更新UI主线程方法之Handler

    背景: 我们开发应用程序的时候,处于线程安全的原因子线程通常是不能直接更新主线程(UI线程)中的UI元素的,那么在Android开发中有几种方法解决这个问题,其中方法之一就是利用Handler处理的. ...

  7. iOS循环引用问题

    今天面试问道了循环引用,所以就看了看,原来只是知道使用了Block容易造成循环引用.今天就来简单的介绍一些循环引用. 先来简单介绍一下什么是循环引用? 循环引用可以简单的理解成:A对象引用了B对象,B ...

  8. 安卓第六天笔记--ListView

    安卓第六天笔记--ListView 1.AdapteView AdapteView 继承ViewGroup它的本质是容器 AdapterView派生了3个子类: AbsListView AbsSpin ...

  9. iOS开发过程中,触控板的使用技巧

    1.在Storyboard鼠标右键可以直接拖线的,如果你用的是外接的第三方鼠标,没必要按着 control 键再用鼠标左键拖线 如果是触控板的话,双指按下去就可以直接拖线,带3Dtouch功能的触控板 ...

  10. IOS之资源收集--很好的github网址

    1.Nick Jensen 2.关于直播的