File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
solution/2000-2099/2097.Valid Arrangement of Pairs Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ #include < vector>
2+ #include < unordered_map>
3+ #include < stack>
4+ using namespace std ;
5+
6+ class Solution {
7+ public:
8+ vector<vector<int >> validArrangement (vector<vector<int >>& pairs) {
9+ unordered_map<int , stack<int >> graph;
10+ unordered_map<int , int > out_degree;
11+
12+ for (auto & p : pairs) {
13+ graph[p[0 ]].push (p[1 ]);
14+ out_degree[p[0 ]]++;
15+ out_degree[p[1 ]]--;
16+ }
17+
18+ int start = pairs[0 ][0 ];
19+ for (auto & [node, degree] : out_degree) {
20+ if (degree > 0 ) {
21+ start = node;
22+ break ;
23+ }
24+ }
25+
26+ vector<vector<int >> result;
27+ stack<int > path;
28+ path.push (start);
29+
30+ while (!path.empty ()) {
31+ int current = path.top ();
32+ if (!graph[current].empty ()) {
33+ path.push (graph[current].top ());
34+ graph[current].pop ();
35+ } else {
36+ if (path.size () > 1 ) {
37+ int end = path.top (); path.pop ();
38+ result.push_back ({path.top (), end});
39+ } else {
40+ path.pop ();
41+ }
42+ }
43+ }
44+
45+ reverse (result.begin (), result.end ());
46+ return result;
47+ }
48+ };
You can’t perform that action at this time.
0 commit comments