题目:

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:

  1. Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree? Show More Hint

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.

链接: http://leetcode.com/problems/graph-valid-tree/

题解:

验证输入数组是否能组成一个树。看了一些资料,这属于并查集的问题。首先我们明确一下满足要求的解的条件:

  1. 题目给定了n个node,则假如能组成一棵树,则这棵树的edge数目为n - 1,所以我们一开始要判断edges.length == n - 1
  2. 不可以有环路,即这个无向图必须是acyclic的, 所有的edges最后也只能组成一个connected components

在判断完edges.length == n - 1后, 我们可以想到使用Union-Find中的Quick-Find。先构造一个长为节点数n的数组id,初始化数组每个元素与他们的index相等。接下来遍历无向图的edges矩阵,假如edges[i][0]和edges[i][1]已经联通,则这个图存在环,我们返回false,否则我们把这两个元素联通起来 - 遍历id数组,将其中所有值为pid的元素值更新为qid。数组遍历结束之后返回true。  Quadratic time还是非常巨大,所以我们还可以继续对这个方法进行优化,接下来的就是Weighted Quick Union + Path Compression了, 留给二刷,继续前进。 收获是接触到了并查集的概念,很高兴。

Time Complexity - O(n2), Space Complexity - O(n)

public class Solution {
public boolean validTree(int n, int[][] edges) { // dynamic connectivity
if(n < 0 || edges == null || edges.length != n - 1)
return false;
int[] id = new int[n];
for(int i = 0; i < id.length; i++) {
id[i] = i;
} for(int i = 0; i < edges.length; i++) {
if(!connected(id, edges[i][0], edges[i][1])) {
union(id, edges[i][0], edges[i][1]);
} else {
return false;
}
}
return true;
} private boolean connected(int[] id, int p, int q) {
return id[p] == id[q];
} private void union(int[] id, int p, int q) {
int pid = id[p];
int qid = id[q];
for(int i = 0; i < id.length; i++) {
if(id[i] == pid) {
id[i] = qid;
}
}
}
}

二刷:

首先检测边界条件, 是否edges.length == n - 1。 其次转化为无向图检测环路,我们可以使用Union-Find来做。

下面是Weighted Quick Union + Path Compression,一如Sedgewick大神教授的。

Java:

public class Solution {
private int[] id;
private int[] sz;
public boolean validTree(int n, int[][] edges) {
if (n < 0 || edges == null || edges.length != n - 1) {
return false;
}
id = new int[n];
sz = new int[n];
for (int i = 0; i < n; i++) {
id[i] = i;
sz[i] = 1;
}
for (int i = 0; i < edges.length; i++) {
if (!isConnected(edges[i][0], edges[i][1])) {
union(edges[i][0], edges[i][1]);
} else {
return false;
}
}
return true;
} private int getRoot(int i) {
while (i != id[i]) {
id[i] = id[id[i]];
i = id[i];
}
return i;
} private void union(int i, int j) {
int rootI = getRoot(i);
int rootJ = getRoot(j);
if (rootI == rootJ) {
return;
}
if (sz[rootI] < sz[rootJ]) {
id[rootI] = rootJ;
sz[rootJ] += sz[rootI];
} else {
id[rootJ] = rootI;
sz[rootI] += sz[rootJ];
}
} private boolean isConnected(int i, int j) {
return getRoot(i) == getRoot(j);
}
}

Reference:

https://en.wikipedia.org/wiki/Disjoint-set_data_structure

https://www.youtube.com/watch?v=4SZTsQO9d6k&index=3&list=PLe-ggMe31CTexoNYnMhbHaWhQ0dvcy43t

https://en.wikipedia.org/wiki/Tree_(data_structure)

http://segmentfault.com/a/1190000003791051

http://blog.csdn.net/dm_vincent/article/details/7655764

http://blog.csdn.net/pointbreak1/article/details/48796691

http://nb4799.neu.edu/wordpress/?p=1143

http://algorithmsandme.in/2014/06/graphs-detecting-cycle-in-undirected-graph/

http://www.cs.nyu.edu/courses/summer04/G22.1170-001/6a-Graphs-More.pdf

https://www.me.utexas.edu/~bard/IP/Handouts/cycles.pdf

https://www.cs.princeton.edu/~rs/AlgsDS07/01UnionFind.pdf

http://www.eecs.wsu.edu/~ananth/CptS223/Lectures/UnionFind.pdf

https://leetcode.com/discuss/52610/8-10-lines-union-find-dfs-and-bfs

https://leetcode.com/discuss/52563/ac-java-union-find-solution

https://leetcode.com/discuss/58600/a-java-solution-with-dfs

https://leetcode.com/discuss/72645/compressed-weighted-quick-union-solution-in-java-2ms

261. Graph Valid Tree的更多相关文章

  1. [LeetCode#261] Graph Valid Tree

    Problem: Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair o ...

  2. [LeetCode] 261. Graph Valid Tree 图是否是树

    Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), ...

  3. [LeetCode] 261. Graph Valid Tree _ Medium tag: BFS

    Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), w ...

  4. [Locked] Graph Valid Tree

    Graph Valid Tree Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is ...

  5. [LeetCode] Graph Valid Tree 图验证树

    Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), ...

  6. Leetcode: Graph Valid Tree && Summary: Detect cycle in undirected graph

    Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), ...

  7. [Swift]LeetCode261.图验证树 $ Graph Valid Tree

    Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), ...

  8. Graph Valid Tree

    Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), ...

  9. LeetCode Graph Valid Tree

    原题链接在这里:https://leetcode.com/problems/graph-valid-tree/ 题目: Given n nodes labeled from 0 to n - 1 an ...

随机推荐

  1. MySQL实战积累

    IFNULL(expr1,expr2)的用法:假如expr1不为NULL,则IFNULL()的返回值为   expr1; 否则其返回值为expr2. 索引:http://www.cnblogs.com ...

  2. Oracle SQL 劈开字符串

    一.数据样例 二.劈开单行 , rownum) h2 FROM (select id_,name_ from test_reg_count t ) CONNECT ; --或者 , rownum) h ...

  3. JNI 学习笔记

    JNI是Java Native Interface的缩写,JNI是一种机制,有了它就可以在java程序中调用其他native代码,或者使native代码调用java层的代码.也 就是说,有了JNI我们 ...

  4. C#学习笔记一

    c#学习笔记一 c#学习笔记一    1 1.    注释    3 1.1.    ///是文档注释,用于类和方法的说明    3 1.2.    #region #endregion可以折叠代码  ...

  5. C# 反射学习总结

    C#中的反射可以使得程序集和类型(类.结构.委托.接口和枚举)以及类型中的成员(方法.字段.属性.事件.参数.构造函数等)都成为变量在编程中动态调用.

  6. 全部快捷方式图标变成LNK文件怎么办

    windowsLNK文件打开方式恢复 相信有些用户曾试过错误地把LNK文件打开方式更改其文件导致系统所有快捷方式都失效vista与Windows7系统还普遍使用时候相信大家会有点惊慌失措要紧下面只要大 ...

  7. phonegap ios插件开发及无限后台运行解决

    1.首先开发插件:因为我的项目前需要所以要做(根据情况) 在项目的plugins文件中新建obj c文件.如 Demo,此时会产生出Demo.h和Demo.m两个文件. .h文件主要就是定义一些方法, ...

  8. C# Windows - 创建控件

    VS提供了一个项目类型Windows Control Library,使用它可以创建自己的控件. 可以开发两种不同类型的自定义控件: 用户或组合控件:这种控件是根据现有控件的功能创建一个新控件.这类控 ...

  9. Careercup - Facebook面试题 - 6299074475065344

    2014-05-01 01:00 题目链接 原题: Given a matrix with 's. What is the maximum area of the rectangle. In . Ho ...

  10. 1066: [SCOI2007]蜥蜴 - BZOJ

    Description 在一个r行c列的网格地图中有一些高度不同的石柱,一些石柱上站着一些蜥蜴,你的任务是让尽量多的蜥蜴逃到边界外. 每行每列中相邻石柱的距离为1,蜥蜴的跳跃距离是d,即蜥蜴可以跳到平 ...