Course Schedule II
操作不当重写了这篇。。
这一周是图的问题
LeetCode上的310题:Minimum Height Trees
题目
对于一个无向无环图,可以选取一个节点作为根,这个图可以看作以该节点为根的树,找出其中高度最低的树的根(可能不止一个)
Example1:
Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]]
0
|
1
/ \
2 3
Output: [1]
Example 2 :
Input: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
0 1 2
\ | /
3
|
4
|
5
Output: [3, 4]
题解
可以用暴力方式对每个节点进行一次DFS算法找到树的节点,但用时太长,这里用的方法是找到图中所有度为1的节点,删除这些节点和这些节点的边,继续找下一批度为1的节点,循环直到节点都被删除,最后一批删除的节点就是所求。
代码
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
if (n == 1) return vector<int>{0};
vector<list<int>> adjacency_list(n);
vector<int> degree(n);
list<int> _list;
vector<int> result;
for (auto edge : edges) {
adjacency_list[edge.first].push_back(edge.second);
adjacency_list[edge.second].push_back(edge.first);
degree[edge.first]++;
degree[edge.second]++;
}
for (int i = 0; i < n; i++) {
if (degree[i] == 1) {
_list.push_back(i);
}
}
while (!_list.empty()) {
result = vector<int>(_list.begin(), _list.end());
for (auto i : result) {
for (auto vetrix : adjacency_list[i]) {
adjacency_list[vetrix].remove(i);
if (--degree[vetrix] == 1) _list.push_back(vetrix);
}
_list.pop_front();
}
}
return result;
}
};