标签:
For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.
Format
The graph contains n
nodes which are labeled from 0
to n - 1
. You will be given the number n
and a list of undirected edges
(each edge is a pair of labels).
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
.
Example 1:
Given n = 4
, edges = [[1, 0], [1, 2], [1, 3]]
0 | 1 / 2 3
return [1]
Example 2:
Given n = 6
, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
0 1 2 \ | / 3 | 4 | 5
return [3, 4]
Solution:
使用二维数组构造图G[N][N],数组G[i]表示节点i的所有相邻节点。数组dist[i]记录节点i的度。
1、根据输入构造图G和数组dist
2、把度位1的节点放入BFS队列Q
3、删除所有度为1的节点,并更新和这些节点相邻的节点的度。当度为1时继续加入队列Q。
4、重复3, 直到剩余节点数<=2
1 vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) 2 { 3 if (n == 1) 4 return {0}; 5 vector<int> result; 6 vector<int> dist(n, 0); 7 vector<vector<int> > G(n, vector<int>()); 8 queue<int> Q; 9 10 // init graph 11 for (auto elem : edges) 12 { 13 G[elem.first].push_back(elem.second); 14 G[elem.second].push_back(elem.first); 15 dist[elem.second]++; 16 dist[elem.first]++; 17 } 18 for (int node = 0; node < dist.size(); node++) 19 { 20 if (dist[node] == 1) 21 Q.push(node); 22 } 23 24 int count = n; 25 while (count > 2) 26 { 27 int qsize = Q.size(); 28 for (int i = 0; i < qsize; i++) 29 { 30 int node = Q.front(); 31 Q.pop(); 32 count--; 33 for (auto elem : G[node]) 34 { 35 dist[elem]--; 36 if (dist[elem] == 1) 37 Q.push(elem); 38 } 39 } 40 } 41 42 while (!Q.empty()) 43 { 44 result.push_back(Q.front()); 45 Q.pop(); 46 } 47 48 return result; 49 }
[leetcode] 310. Minimum Height Trees
标签:
原文地址:http://www.cnblogs.com/ym65536/p/5790022.html