forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0332.cpp
More file actions
executable file
·37 lines (32 loc) · 793 Bytes
/
LC0332.cpp
File metadata and controls
executable file
·37 lines (32 loc) · 793 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/reconstruct-itinerary/
Time: O(E • log E)
Space: O(E)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
vector<string> order;
unordered_map<string, vector<string>> adj;
// hierholzer's algorithm
function<void(string)> dfs = [&](string s) {
vector<string>& v = adj[s];
while (!v.empty()) {
string u = v.back();
v.pop_back();
dfs(u);
}
order.push_back(s);
};
// construct adjacency list
for (auto& t: tickets)
adj[t[0]].push_back(t[1]);
for (auto& [k, v]: adj)
sort(v.rbegin(), v.rend());
// euler path finding
dfs("JFK");
reverse(order.begin(), order.end());
return order;
}
};