File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ vector<vector<int>> validArrangement(vector<vector<int>>& pairs) {
4+
5+ vector<vector<int>> ans;
6+ unordered_map<int, int> mp;
7+ unordered_map<int, vector<int>> adj;
8+
9+ for (auto it : pairs) {
10+ mp[it[0]]++;
11+ mp[it[1]]--;
12+ adj[it[0]].push_back(it[1]);
13+ }
14+
15+ //finding start node
16+ int starting = pairs[0][0];
17+ for (auto it : mp) {
18+ if (it.second == 1) {
19+ starting = it.first;
20+ break;
21+ }
22+ }
23+
24+ vector<int> ref;
25+ stack<int> st;
26+ st.push(starting);
27+ //dfs
28+ while (st.size()) {
29+ auto& nodes = adj[st.top()];
30+ if (nodes.empty()) {
31+ ref.push_back(st.top());
32+ st.pop();
33+ } else {
34+ st.push(nodes.back());
35+ nodes.pop_back();
36+ }
37+ }
38+ // converting the path
39+ for (int i = ref.size() - 1; i > 0; i--) {
40+ ans.push_back({ref[i], ref[i - 1]});
41+ }
42+
43+ return ans;
44+ }
45+ };
You can’t perform that action at this time.
0 commit comments