码迷,mamicode.com
首页 > 其他好文 > 详细

261. Graph Valid Tree

时间:2016-03-23 13:09:11      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

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:

  1. Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree? 
  2. According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”

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.

Similar: 
  • 207. Course Schedule
  • 323. Number of Connected Components in an Undirected Graph
 1 public class Solution {
 2     public boolean validTree(int n, int[][] edges) {
 3         int[] pt = new int[n];
 4         for (int i=0; i<n; i++) { pt[i] = i; }
 5         
 6         for (int[] edge : edges) {
 7             int root1 = find(pt, edge[0]);
 8             int root2 = find(pt, edge[1]);
 9             
10             if (root1 == root2) return false; // find circle
11             
12             pt[root1] = root2; // union
13         }
14         return edges.length == n-1; // tree w/ n notes have n-1 edges
15     }
16     private int find(int[] pt, int i) {
17         while (pt[i] != i) {
18             pt[i] = pt[pt[i]];
19             i = pt[i];
20         }
21         return i;
22     }
23 }

 

261. Graph Valid Tree

标签:

原文地址:http://www.cnblogs.com/joycelee/p/5310560.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!