-
Notifications
You must be signed in to change notification settings - Fork 111
/
reconstruct-itinerary.cc
51 lines (48 loc) · 1.19 KB
/
reconstruct-itinerary.cc
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
// Reconstruct Itinerary
/// Hierholzer's algorithm (lexicographical order)
class Solution {
unordered_map<string, vector<string>> m;
vector<string> ret;
void hierholzer(string x) {
while (! m[x].empty()) {
string y = m[x].back();
m[x].pop_back();
hierholzer(y);
}
ret.push_back(x);
}
public:
vector<string> findItinerary(vector<vector<string>> &tickets) {
sort(tickets.begin(), tickets.end(), greater<>());
for (auto &x: tickets)
m[x[0]].push_back(x[1]);
hierholzer("JFK");
reverse(ret.begin(), ret.end());
return ret;
}
};
/// non-recursive Hierholzer's algorithm
class Solution {
public:
vector<string> findItinerary(vector<vector<string>> &tickets) {
sort(tickets.begin(), tickets.end(), greater<>());
unordered_map<string, vector<string>> m;
for (auto &x: tickets)
m[x[0]].push_back(x[1]);
stack<string> st;
vector<string> ret;
st.push("JFK");
while (! st.empty()) {
auto &x = st.top();
if (m[x].empty()) {
ret.push_back(x);
st.pop();
} else {
st.push(m[x].back());
m[x].pop_back();
}
}
reverse(ret.begin(), ret.end());
return ret;
}
};