Graph Valid Tree
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), write a function to check whether these edges make up a valid tree.
Example
Given n = 5
andedges = [[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.
Note
View Code
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.
这一题lintcode上的中文我并不能理解是什么意思。。于是就放上英文的。
大意是给你一个图的节点数n,和边的集合(整型二维数组),检验这个图是不是一棵树。
一个图是不是一棵树,要看这个图是否是连通的,不连通的当然不是树。
还要看有没有环,树是没有环的。
用并查集(应该是这么叫把?)的方法,将点合并,期间发现有环则 return false。
然后检验是否联通,若有一点不连通则return false。
1 public class Solution { 2 /** 3 * @param n an integer 4 * @param edges a list of undirected edges 5 * @return true if it's a valid tree, or false 6 */ 7 public boolean validTree(int n, int[][] edges) { 8 int flag[] = new int[n]; 9 for(int i=0;i<n;i++) { 10 flag[i] = i; 11 } 12 13 for(int i=0;i<edges.length;i++) { 14 int s = edges[i][0]; 15 int e = edges[i][1]; 16 if(flag[s] != flag[e]) { 17 int x = flag[e]; 18 for(int j=0;j<n;j++) { 19 if(flag[j] == x) flag[j] = flag[s]; 20 } 21 }else return false; 22 } 23 24 25 26 for(int i=1;i<n;i++) { 27 if(flag[0] != flag[i])return false; 28 } 29 30 return true; 31 } 32 }