-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathreconstruct-itinerary.cpp
73 lines (65 loc) · 2.16 KB
/
reconstruct-itinerary.cpp
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Time: O(|V| + |E|log|V|)
// Space: O(|V| + |E|)
// Hierholzer Algorithm
class Solution {
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
static const string origin{"JFK"};
unordered_map<string, vector<string>> adj;
for (const auto& ticket : tickets) {
adj[ticket[0]].emplace_back(ticket[1]);
}
for (auto& [k, v] : adj) {
sort(rbegin(v), rend(v));
}
vector<string> result;
vector<string> stk = {origin};
while (!empty(stk)) {
while (!empty(adj[stk.back()])) {
auto x = adj[stk.back()].back();
adj[stk.back()].pop_back();
stk.emplace_back(x);
}
result.emplace_back(stk.back());
stk.pop_back();
}
reverse(begin(result), end(result));
return result;
}
};
// Time: O(t! / (n1! * n2! * ... nk!)), t is the total number of tickets,
// ni is the number of the ticket which from is city i,
// k is the total number of cities.
// Space: O(t)
class Solution2 {
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
unordered_map<string, map<string, int>> graph;
for (const auto& ticket : tickets) {
++graph[ticket[0]][ticket[1]];
}
const string from{"JFK"};
vector<string> ans{from};
routeHelper(from, tickets.size(), &graph, &ans);
return ans;
}
private:
bool routeHelper(const string& from, const int ticket_cnt,
unordered_map<string, map<string, int>> *graph, vector<string> *ans) {
if (ticket_cnt == 0) {
return true;
}
for (auto& to : (*graph)[from]) {
if (to.second) {
--to.second;
ans->emplace_back(to.first);
if (routeHelper(to.first, ticket_cnt - 1, graph, ans)) {
return true;
}
ans->pop_back();
++to.second;
}
}
return false;
}
};