Leetcode 332 Solution

This article provides solution to leetcode question 332 (reconstruct-itinerary)

https://leetcode.com/problems/reconstruct-itinerary

Solution

class Solution {
public:
    vector<string> findItinerary(vector<pair<string, string> > tickets) {
        vector<string> res;
        unordered_map<string, multiset<string> > m;
        for (auto a : tickets) {
            m[a.first].insert(a.second);
        }
        dfs(m, "JFK", res);
        return vector<string> (res.rbegin(), res.rend());
    }
    void dfs(unordered_map<string, multiset<string> > &m, string s, vector<string> &res) {
        while (m[s].size()) {
            string t = *m[s].begin();
            m[s].erase(m[s].begin());
            dfs(m, t, res);
        }
        res.push_back(s);
    }
};