Skip to content

Commit a438e3e

Browse files
authored
Create 2097.Valid-Arrangement-of-Pairs.cpp
1 parent 7ebf8ae commit a438e3e

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
};

0 commit comments

Comments
 (0)