File tree Expand file tree Collapse file tree
Graph/2097.Valid-Arrangement-of-Pairs Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution {
2+ unordered_map<int ,vector<int >>Map;
3+ unordered_map<int ,int >in;
4+ unordered_map<int ,int >out;
5+
6+ public:
7+ vector<vector<int >> validArrangement (vector<vector<int >>& pairs)
8+ {
9+
10+ for (auto pair: pairs)
11+ {
12+ Map[pair[0 ]].push_back (pair[1 ]);
13+ in[pair[1 ]]++;
14+ out[pair[0 ]]++;
15+ }
16+
17+ int start = -1 ;
18+ for (auto x: Map)
19+ {
20+ int p = x.first ;
21+ if (out[p]-in[p]==1 )
22+ start = p;
23+ }
24+
25+ if (start==-1 )
26+ start = pairs[0 ][0 ];
27+
28+ vector<int >path;
29+ DFS (start, path);
30+ reverse (path.begin (), path.end ());
31+
32+ vector<vector<int >>rets;
33+ for (int i=0 ; i<path.size ()-1 ; i++)
34+ rets.push_back ({path[i], path[i+1 ]});
35+ return rets;
36+ }
37+
38+
39+ void DFS (int start, vector<int >& path)
40+ {
41+ while (Map[start].size ()>0 )
42+ {
43+ int nextStart = Map[start].back ();
44+ Map[start].pop_back ();
45+ DFS (nextStart, path);
46+ }
47+ path.push_back (start);
48+ }
49+ };
You can’t perform that action at this time.
0 commit comments