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. The type java.util.Map$Entry cannot be resolved. It is indirectly referenced。。.相似的错误

    这个问题是出现一般都是因为JDK版本的问题.今天公司安装NC的时候就出现了这个问题.经过对错误的分析和猜测,将JDK从1.8i换成了1.7,之后就行了.根据我个人的猜测,可能是1.8以后就不支持Map ...

  2. 泛函编程(16)-泛函状态-Functional State

    初接触泛函状态觉着很不习惯.主要是在使用State数据类型时很难理解其中的原理,特别是泛函状态变迁机制(state transition mechanism):怎么状态就起了变化,实在难以跟踪.我想这 ...

  3. IIS在默认情况并不支持对PUT和DELETE请求的支持

    IIS在默认情况并不支持对PUT和DELETE请求的支持: IIS拒绝PUT和DELETE请求是由默认注册的一个名为:“WebDAVModule”的自定义HttpModule导致的.WebDAV的全称 ...

  4. android的Project has no default.properties file! Edit the project properties to set one. 的解决

    网上找来这种方法基本解决: 在我们导入Android工程时,有时候会出现如题所述的错误,打开工程目录可以看到,目录下的default.properties文件没有了或者多出了一个project.pro ...

  5. Design Patterns (简单工厂模式)

    文章很长很精彩,如是初学请耐心观看.(大神请绕道!) 简单工厂模式: 1.创建型模式 2.简单工厂模式概述 3.简单工厂模式的结构与实现 4.简单工厂模式的应用实例 5.创建对象与使用对象 6.简单工 ...

  6. [iOS] 使用xib做为应用程序入口 with Code

    [iOS] 使用xib做为应用程序入口 with Code 前言 开发iOS APP的时候,使用storyboard能够快速并且直觉的建立用户界面.但在多人团队开发的情景中,因为storyboard是 ...

  7. swift学习笔记之-继承

    //继承 import UIKit /* 继承(Inheritance): 1.一个类可以继承(inherit)另一个类的方法(methods).属性(properties)和其它特性.当一个类继承其 ...

  8. 初学Node(一)国际惯例HelloWorld

    简介 没有用过Node,记的这些只是学习的笔记,有什么错的地方,望各位前辈指正. Node是一个服务器端Javascript解释器,依赖于Chrome v8引擎进行代码编译,事件驱动.非阻塞I/O都是 ...

  9. 使用RDCMan管理SharePoint虚拟机的重复要求验证的问题

    首先,这个软件可以从这里下载: Remote Desktop Connection Manager 同类型的软件还有很多,我没有很多复杂功能的要求,就选择了这款微软官方的,虽然很久都没有更新过了. 为 ...

  10. Android WelcomeActivity 启动画更换网络图片

    1.运行效果  第一张是本地的启动图,第二张是网络启动图       2.用到的第三方jar包   Android-Universal-Image-Loader-master 不熟的请看  Andro ...