diff --git a/InSange/DFS/2097 Valid Arrangement of Pairs.cpp b/InSange/DFS/2097 Valid Arrangement of Pairs.cpp new file mode 100644 index 0000000..9f883e5 --- /dev/null +++ b/InSange/DFS/2097 Valid Arrangement of Pairs.cpp @@ -0,0 +1,64 @@ +#include +#include +#include + +using namespace std; + +class Solution { +public: + unordered_map> nodes; + unordered_map inDegree; + unordered_map outDegree; + + vector result; + + void DFS(int index) + { + while (!nodes[index].empty()) + { + int nextNode = nodes[index].front(); + nodes[index].pop_front(); + DFS(nextNode); + } + result.push_back(index); // ᱹ. 湮ߴٸ. ִ 忡 湮ߴٸ ΰ Ųٷ ̾ . + } + + vector> validArrangement(vector>& pairs) { + for (const vector& pair : pairs) + { + int depart = pair[0]; + int dest = pair[1]; + + nodes[depart].push_back(dest); + inDegree[dest]++; + outDegree[depart]++; + } + + int startNode = -1; + + for (const auto& degree : outDegree) + { + int curNode = degree.first; + if (outDegree[curNode] == inDegree[curNode] + 1) // 忡 + 1 . ٽ ش 带 ľ 带 湮 . + { + startNode = curNode; + break; + } + } + + if (startNode == -1) // 带 ߰ ߴٸ ϳ , ϰ + { + startNode = pairs[0][0]; + } + + DFS(startNode); + + vector> ans; + for (int i = result.size() - 1; i > 0; i--) + { + ans.push_back({ result[i], result[i - 1] }); // Ųٷ + } + + return ans; + } +}; \ No newline at end of file diff --git a/InSange/README.md b/InSange/README.md index 48462ff..b73134a 100644 --- a/InSange/README.md +++ b/InSange/README.md @@ -32,6 +32,7 @@ | 28차시 | 2024.08.21 | 백트래킹 | [월드컵](https://www.acmicpc.net/problem/6987) | [#28](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/94)] | 29차시 | 2024.08.25 | 문자열 | [Find the Closest Palindrome](https://leetcode.com/problems/find-the-closest-palindrome/) | [#29](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/98)] | 30차시 | 2024.09.06 | 문자열 | [Delete Nodes From Linked List Present in Array](https://leetcode.com/problems/delete-nodes-from-linked-list-present-in-array/) | [#30](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/100)] +| 31차시 | 2024.12.01 | DFS | [Valid Arrangement of Pairs](https://leetcode.com/problems/valid-arrangement-of-pairs/) | [#31](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/101)] --- https://leetcode.com/problems/robot-collisions/