forked from shruti170901/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReconstruct Itinerary.cpp
45 lines (41 loc) · 1.05 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
class Solution {
unordered_map<string, multiset<string>> G;
vector<string> R;
public:
vector<string> findItinerary(vector<vector<string>>& T) {
for (auto &t : T)
G[t[0]].insert(t[1]);
dfs("JFK");
return vector<string>(R.rbegin(), R.rend());
}
void dfs(const string &s) {
while (!G[s].empty()) {
auto it = G[s].begin();
auto n = *it;
G[s].erase(it);
dfs(n);
}
R.push_back(s);
}
};
///////////////////////////////////////////////////////////////////////////////////////////////
class Solution {
public:
unordered_map<string, multiset<string>> edges;
vector<string> route;
void dfs(string cur){
while(!edges[cur].empty()){
string next = *edges[cur].begin();
edges[cur].erase(edges[cur].begin());
dfs(next);
}
route.insert(route.begin(), cur);
}
vector<string> findItinerary(vector<vector<string>>& tickets) {
for(vector<string>& ticket : tickets){
edges[ticket[0]].insert(ticket[1]);
}
dfs("JFK");
return route;
}
};