LintCode_178 Graph Valid Tree
来源:互联网 发布:淘宝直通车品牌资质 编辑:程序博客网 时间:2024/04/27 22:47
Given n
nodes labeled from 0
to n - 1
and a list ofundirected
edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
Notice
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.
Example
思路是用并查集实现,如果一条边的两个点有相同的parent,意味着两个点属于一个集合, 所以必回形成环,所以就不是tree;Given n = 5
and edges = [[0, 1], [0, 2], [0, 3], [1, 4]]
, return true.
Given n = 5
andedges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]
, return false.
最后还要检查下有几个集合, 如果多余一个, 说明没连起来, 索爷也不是tree;
class Solution {public: /** * @param n an integer * @param edges a list of undirected edges * @return true if it's a valid tree, or false */ bool validTree(int n, vector<vector<int>>& edges) { // Write your code here vector<int> linkedset; if (n == 1 && edges.empty()) return true; for (int i = 0; i < n; i++) { linkedset.push_back(i); } for (int i = 0; i < edges.size(); i++) { int root1= get_root(edges[i][0], linkedset); int root2= get_root(edges[i][1], linkedset); if (root1 == root2) return false; if (root1 > root2) { linkedset[root1] = root2; } else { linkedset[root2] = root1; } } int num_of_root = 0; for (int i = 0; i < linkedset.size(); i++) { if (linkedset[i] == i) num_of_root++; } if (num_of_root != 1) return false; else return true; } int get_root(int i, vector<int>& linkedset) { while (linkedset[i] != i) { i = linkedset[i]; } return i; }};
0 0
- LintCode_178 Graph Valid Tree
- [Leetcode]Graph Valid Tree
- Graph Valid Tree
- [LeetCode261] Graph Valid Tree
- 261. Graph Valid Tree
- lintcode:Graph Valid Tree
- Graph Valid Tree
- Graph Valid Tree
- leetcode Graph Valid Tree
- Leetcode Graph Valid Tree
- LeetCode Graph Valid Tree
- Graph Valid Tree
- 261. Graph Valid Tree
- Graph Valid Tree
- 261. Graph Valid Tree
- Graph Valid Tree
- Graph Valid Tree
- Leetcode - 261. Graph Valid Tree
- eclipse启动tomcat无法访问的解决方法
- c#委托与事件的应用
- Closest Binary Search Tree Value
- 利用dll创建窗口的一些学习过程
- myeclipse项目转web项目
- LintCode_178 Graph Valid Tree
- Hi3798 Alsa 驱动分析
- JAVA SE8 OCA/OCP和PL/SQL OCA/OCP认证书籍推荐
- 热血江湖-术语整理
- dom4j解析xml
- Logger Rate Limiter
- 第43课:Spark Streaming中UI内幕实现彻底解密
- Reverse a sentence
- Java中Map和Vector集合