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.

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? 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.

 1 public boolean validTree(int n, int[][] edges) {
 2     HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
 3     for(int i=0; i<n; i++){
 4         ArrayList<Integer> list = new ArrayList<Integer>();
 5         map.put(i, list);
 6     }
 7  
 8     for(int[] edge: edges){
 9         map.get(edge[0]).add(edge[1]);
10         map.get(edge[1]).add(edge[0]);
11     }
12  
13     boolean[] visited = new boolean[n];
14  
15     LinkedList<Integer> queue = new LinkedList<Integer>();
16     queue.offer(0);
17     while(!queue.isEmpty()){
18         int top = queue.poll();
19         if(visited[top])
20             return false;
21  
22         visited[top]=true;
23  
24         for(int i: map.get(top)){
25             if(!visited[i])
26                 queue.offer(i);
27         }
28     }
29  
30     for(boolean b: visited){
31         if(!b)
32             return false;
33     }
34  
35     return true;
36 }

 

 1 public class Solution {
 2     public boolean validTree(int n, int[][] edges) {
 3         // initialize n isolated islands
 4         int[] nums = new int[n];
 5         Arrays.fill(nums, -1);
 6         
 7         // perform union find
 8         for (int i = 0; i < edges.length; i++) {
 9             int x = find(nums, edges[i][0]);
10             int y = find(nums, edges[i][1]);
11             
12             // if two vertices happen to be in the same set
13             // then there's a cycle
14             if (x == y) return false;
15             // union
16             nums[x] = y;
17         }        
18         return edges.length == n - 1;
19     }
20     
21     int find(int nums[], int i) {
22         if (nums[i] == -1) return i;
23         return find(nums, nums[i]);
24     }
25 }

 

posted @ 2016-10-14 02:56  北叶青藤  阅读(263)  评论(0编辑  收藏  举报