// Reconstruct Itinerary /// Hierholzer's algorithm class Solution { unordered_map> m; vector ret; void hierholzer(string x) { while (! m[x].empty()) { string y = *m[x].begin(); m[x].erase(m[x].begin()); hierholzer(y); } ret.push_back(x); } public: vector findItinerary(vector> tickets) { for (auto &x: tickets) m[x.first].insert(x.second); hierholzer("JFK"); reverse(ret.begin(), ret.end()); return ret; } }; /// non-recursive Hierholzer's algorithm class Solution { public: vector findItinerary(vector> tickets) { unordered_map> m; for (auto &x: tickets) m[x.first].insert(x.second); stack st; vector ret; st.push("JFK"); while (! st.empty()) { auto &x = st.top(); if (m[x].empty()) { ret.push_back(x); st.pop(); } else { auto it = m[x].begin(); st.push(*it); m[x].erase(it); } } reverse(ret.begin(), ret.end()); return ret; } };