-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cpp
33 lines (28 loc) · 952 Bytes
/
Solution.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
class Solution {
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
unordered_map<string, priority_queue<string, vector<string>, greater<string>>> g;
vector<string> ret;
// Initialize the graph
for (const auto& t : tickets) {
g[t[0]].push(t[1]);
}
findItineraryInner(g, ret, "JFK");
ret = {ret.rbegin(), ret.rend()};
return ret;
}
void findItineraryInner(unordered_map<string, priority_queue<string, vector<string>, greater<string>>>& g, vector<string>& ret, string cur) {
if (g.count(cur) == 0) {
// This is the end point
ret.push_back(cur);
return;
} else {
while (!g[cur].empty()) {
auto front = g[cur].top();
g[cur].pop();
findItineraryInner(g, ret, front);
}
ret.push_back(cur);
}
}
};