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

Leetcode 261: Graph Valid Tree

时间:2018-01-20 10:57:58      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:contain   pre   code   nta   air   direct   gpo   hat   color   

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.

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 class Solution {
 2     // what is graph valid tree? 1: all the nodes are connected 2: no cycle
 3     public bool ValidTree(int n, int[,] edges) {
 4         var al = new Dictionary<int, HashSet<int>>();
 5         
 6         for (int i = 0; i < edges.GetLength(0); i++)
 7         {
 8             var v1 = edges[i, 0];
 9             var v2 = edges[i, 1];
10             
11             if (!al.ContainsKey(v1))
12             {
13                 al[v1] = new HashSet<int>();
14             }
15             
16             al[v1].Add(v2);
17             
18             if (!al.ContainsKey(v2))
19             {
20                 al[v2] = new HashSet<int>();
21             }
22             
23             al[v2].Add(v1);
24         }
25         
26         // make sure we can traverse all the nodes from root and there is no cycle
27         var queue = new Queue<int>();
28         queue.Enqueue(0);
29         var visited = new bool[n];
30         
31         while (queue.Count > 0)
32         {
33             var node = queue.Dequeue();
34             
35             if (visited[node])
36             {
37                 return false;
38             }
39             
40             visited[node] = true;
41             
42             if (al.ContainsKey(node) && al[node] != null)
43             {
44                 foreach (var nn in al[node])
45                 {
46                     // as we already traverse node -> nn, we need to remove the edge from nn -> node as traversing tree is one way only
47                     al[nn].Remove(node);
48                     queue.Enqueue(nn);
49                 }
50             }
51         }
52         
53         for (int i = 0; i < n; i++)
54         {
55             if (!visited[i]) return false;
56         }
57         
58         return true;
59     }
60 }

 

Leetcode 261: Graph Valid Tree

标签:contain   pre   code   nta   air   direct   gpo   hat   color   

原文地址:https://www.cnblogs.com/liangmou/p/8319785.html

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