-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path2097.cpp
More file actions
40 lines (37 loc) · 1.15 KB
/
2097.cpp
File metadata and controls
40 lines (37 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public:
void dfs(unordered_map<int, stack<int>>& graph, vector<vector<int>>& res, int curr) {
auto& neighbors = graph[curr];
while (!neighbors.empty()) {
int neighbor = neighbors.top();
neighbors.pop();
dfs(graph, res, neighbor);
res.push_back({curr, neighbor});
}
}
vector<vector<int>> validArrangement(vector<vector<int>>& pairs) {
unordered_map<int, stack<int>> graph;
unordered_map<int, int> in;
unordered_map<int, int> out;
for (const auto& pair : pairs) {
int u = pair[0];
int v = pair[1];
graph[u].push(v);
in[v]++;
out[u]++;
}
int start = -1;
for (auto& element : graph) {
int node = element.first;
if (out[node] - in[node] == 1) {
start = node;
break;
}
}
if (start == -1) start = graph.begin()->first;
vector<vector<int>> res;
dfs(graph, res, start);
reverse(res.begin(), res.end());
return res;
}
};