/* * 261.Graph Valid Tree * 2016-3-29 by Buttercola * 和上面的BFS方法一样,不过这里是无向图,所以需要两个点都要存对方 * 图要形成树必须有两个方面,一个是没有cycle另一个是没有孤立的点 */ public boolean validTree(int n, int[][] edges) { // build the graph using adjacent list HashMap<Integer,HashSet<Integer>> graph=new HashMap<Integer,HashSet<Integer>>(); for(int i = 0; i < n; i++) graph.put(i,new HashSet<Integer>()); for(int[] edge : edges) { graph.get(edge[0]).add(edge[1]); graph.get(edge[1]).add(edge[0]); } // no cycle boolean[] visited = new boolean[n]; Queue<Integer> queue = new LinkedList<Integer>(); queue.add(0); while(!queue.isEmpty()) { int node = queue.poll(); if(visited[node]) return false; visited[node] = true;//保证每个点都访问到 for(int neighbor : graph.get(node)) { queue.offer(neighbor);//找到所有的邻接点,并且砍掉回来的路 graph.get(neighbor).remove((Integer)node); } } // fully connected for(boolean result : visited){ if(!result) return false; } return true; }
当然我们也可以用Union Find的方法来做,更简单!
public boolean validTree(int n, int[][] edges) { // initialize n isolated islands int[] nums = new int[n]; Arrays.fill(nums, -1); // perform union find for (int i = 0; i < edges.length; i++) { int x = find(nums, edges[i][0]); int y = find(nums, edges[i][1]); // if two vertices happen to be in the same set // then there's a cycle if (x == y) return false; // union nums[x] = y; } return edges.length == n - 1; } int find(int nums[], int i) { if (nums[i] == -1) return i; return find(nums, nums[i]); }