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. 访问WEB-INFO 目录注意事项

    WEB-INF下面的内容都是只能由服务器级别才能访问,客户端并不能访问.什么是客户端级别?什么是服务器级别呢? 转发就是服务器级别,浏览器的地址不会变,因为,客户端发送一个请求,服务器受理之后,发现要 ...

  2. 我见过的几门语言中的hello world

    1.Java public class hello { public static void main(String[] args){ System.out.println("hello w ...

  3. php对mysql数据库简单连接操作

    前些阵子忙完了公司前端静态页面的事情了之后,简单学习了下php的基础知识,今天想了想回顾一下php连接数据库的方式,写一下随笔存一下看看 php连接数据库端口和新建数据库 <?php $serv ...

  4. SharePoint 2013: Search Architecture in SPC202

    http://social.technet.microsoft.com/wiki/contents/articles/15989.sharepoint-2013-search-architecture ...

  5. 错误:StrictMode $ AndroidBlockGuardPolicy.onNetwork

    you have to insert 2 lines "StrictMode" on MainActivity Class, example's below: 在onCreate( ...

  6. 关于破解IDEA

    博客的意义就在于分享 哈哈 今天想装个 IDEA玩玩 去官网 下了个 安装包 想破解 结果度娘 帮解决了 直接po方法 很简单 就是安装好注册的时候 选择 License server ,填 http ...

  7. UVa 104 - Arbitrage(Floyd动态规划)

    题目来源:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&pa ...

  8. Android中ListView 控件与 Adapter 适配器如何使用?

    一个android应用的成功与否,其界面设计至关重要.为了更好的进行android ui设计,我们常常需要借助一些控件和适配器.今天小编在android培训网站上搜罗了一些有关ListView 控件与 ...

  9. 深入理解java虚拟机(3)---类的结构

    计算机在开始的时候,只认识0和1,所以汇编语言是和机器结构或者说CPU绑定的.ARM体系结构就是这样一种体现,指令集的概念. 随着高级语言的出现,从字编码发展到了字节编码,计算机的先驱希望能够让语言能 ...

  10. crontab 例行性排程

    那么我们就来聊一聊 crontab 的语法吧![root@www ~]# crontab [-u username] [-l|-e|-r]选项不参数:-u :只有 root 才能迚行这个仸务,亦即帮其 ...