標籤:
Graph Valid TreeGiven 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.Have you met this question in a real interview? YesExample
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
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 }View Code
Graph Valid Tree