diff --git a/InSange/BFS/310_Minimum Height Trees.cpp b/InSange/BFS/310_Minimum Height Trees.cpp new file mode 100644 index 0000000..d482392 --- /dev/null +++ b/InSange/BFS/310_Minimum Height Trees.cpp @@ -0,0 +1,66 @@ +#include +#include +#include + +using namespace std; + +class Solution { +public: + vector findMinHeightTrees(int n, vector>& edges) { + map> m; + vector ans; + vector check(n, false); + int* degree = new int[n] {0}; + + for (vector node : edges) + { + m[node[0]].push_back(node[1]); + m[node[1]].push_back(node[0]); + degree[node[0]]++; + degree[node[1]]++; + } + int current_n = n; + + queue q; + if (current_n > 2) + { + for (int i = 0; i < n; i++) + { + if (degree[i] == 1 && check[i] == false) + { + check[i] = true; + q.push(i); + current_n--; + } + } + } + while (current_n > 2 && !q.empty()) + { + int size = q.size(); + + for (int j = 0; j < size; j++) + { + int remove_n = q.front(); + q.pop(); + + for (auto node : m[remove_n]) + { + degree[node]--; + if (degree[node] == 1) + { + q.push(node); + check[node] = true; + current_n--; + } + } + } + } + + for (int i = 0; i < n; i++) + { + if (check[i] == false) ans.push_back(i); + } + + return ans; + } +}; \ No newline at end of file diff --git a/InSange/README.md b/InSange/README.md index 537b1a9..13400de 100644 --- a/InSange/README.md +++ b/InSange/README.md @@ -26,6 +26,7 @@ | 22차시 | 2024.07.31 | DP | [Filling Bookcase Shelves](https://leetcode.com/problems/filling-bookcase-shelves/) | [#22](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/81)] | 23차시 | 2024.08.03 | 슬라이딩 윈도우 | [Minimum Swaps to Group All 1's Together 2](https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/) | [#23](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/82)] | 24차시 | 2024.08.04 | BFS | [트리](https://www.acmicpc.net/problem/1068) | [#24](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/83)] +| 25차시 | 2024.08.10 | BFS | [Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees/) | [#25](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/87)] --- https://leetcode.com/problems/robot-collisions/