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

# 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.

# For example:

# Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.

# Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.

# Hint:

# Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree?
# 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.”
# 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. # Hide Company Tags Google Facebook Zenefits
# Hide Tags Depth-first Search Breadth-first Search Graph Union Find
# Hide Similar Problems (M) Course Schedule (M) Number of Connected Components in an Undirected Graph class Solution(object):
def validTree(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: bool
"""
parents = range(n)
self.count = n
def find(x):
if parents[x]!=x:
parents[x]=find(parents[x]) return parents[x] def union(x,y):
x,y = find(x),find(y)
if x!=y:
parents[x]=y
self.count-=1
return True
return False for e in edges:
if not union(e[0], e[1]):
return False return self.count==1 sol = Solution()
assert sol.validTree(5, [[0, 1], [0, 2], [0, 3], [1, 4]])==True
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. jQuery中的事件冒泡

    1.什么是冒泡 eg: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <he ...

  2. .NET AES加解密(128位)

    AES加密(128位): /// <summary> /// 有密码的AES加密 /// </summary> internal static string Encrypt(s ...

  3. [Xamarin.Android] 使用Component套件

    [Xamarin.Android] 使用Component套件 前言 在Xamarin中,可以将自己开发的项目包装成为Component套件发布至Xamarin Component Store,来提供 ...

  4. oracle10g 统计信息查看、收集

      1. 统计信息查看 1.1 单个表的全局统计信息.统计效果查看 2. 统计信息分析(收集) 2.1 分析工具选择 2.2 分析前做index重建 2.3 分析某数据表,可以在PL/SQL的comm ...

  5. FileInputStream类

    FileInputStream和FileOutPutStream类都是用来操作磁盘文件的.如果用户对文件读取需求比较简单,则可以使用FileInputStream类,该类继承InputStream类 ...

  6. File类的常用方法

    public static void GetFileInfo()    {                File file=new File("e:","two.txt ...

  7. Spring中配置数据源的4种形式(转)

    原文http://blog.csdn.net/orclight/article/details/8616103       不管采用何种持久化技术,都需要定义数据源.Spring中提供了4种不同形式的 ...

  8. 【iOS开发】UIWebView与JavaScript(JS) 回调交互

    ------------------------------------------------- 很多关于objc 与 js 交互的文章都比较适用于 mac开发,iOS的webview 还是有所不一 ...

  9. 关于配置并发访问的服务器apache、nginx

    一. apache,nginx比较     关于Apache与Nginx的优势比较  (apache计算密集型   nginx io密集型  各有优势,不存在谁取代谁) 二.nginx 基于nginx ...

  10. 记录Hibernate的缓存知识

    一.Hibernate缓存的作用 Hibernate是一个持久层框架,Hibernate要经常访问物理数据库.为了降低应用程序对物理数据源访问的频次,从而提高应用程序的运行性能,Hibernate的缓 ...