1. 程式人生 > >[LeetCode] Reconstruct Itinerary 重建行程單

[LeetCode] Reconstruct Itinerary 重建行程單

Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.

Note:

  1. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"]
     has a smaller lexical order than ["JFK", "LGB"].
  2. All airports are represented by three capital letters (IATA code).
  3. You may assume all tickets may form at least one valid itinerary.

Example 1:
tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Return ["JFK", "MUC", "LHR", "SFO", "SJC"]

.

Example 2:
tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Return ["JFK","ATL","JFK","SFO","ATL","SFO"].
Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order.

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

這道題給我們一堆飛機票,讓我們建立一個行程單,如果有多種方法,取其中字母順序小的那種方法。這道題的本質是有向圖的遍歷問題,那麼LeetCode關於有向圖的題只有兩道Course ScheduleCourse Schedule II,而那兩道是關於有向圖的頂點的遍歷的,而本題是關於有向圖的邊的遍歷。每張機票都是有向圖的一條邊,我們需要找出一條經過所有邊的路徑,那麼DFS不是我們的不二選擇。先來看遞迴的結果,我們首先把圖建立起來,通過鄰接連結串列來建立。由於題目要求解法按字母順序小的,那麼我們考慮用multiset,可以自動排序。等我們圖建立好了以後,從節點JFK開始遍歷,只要當前節點對映的multiset裡有節點,我們取出這個節點,將其在multiset裡刪掉,然後繼續遞迴遍歷這個節點,由於題目中限定了一定會有解,那麼等圖中所有的multiset中都沒有節點的時候,我們把當前節點存入結果中,然後再一層層回溯回去,將當前節點都存入結果,那麼最後我們結果中存的順序和我們需要的相反的,我們最後再翻轉一下即可,參見程式碼如下:

解法一:

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);
    }
};

下面我們來看迭代的解法,需要藉助棧來實現,來實現回溯功能。比如對下面這個例子:

tickets = [["JFK", "KUL"], ["JFK", "NRT"], ["MRT", "JFK"]]

那麼建立的圖如下:

JFK -> KUL, NRT

NRT -> JFK

由於multiset是按順序存的,所有KUL會在NRT之前,那麼我們起始從JFK開始遍歷,先到KUL,但是KUL沒有下家了,這時候圖中的邊並沒有遍歷完,此時我們需要將KUL存入棧中,然後繼續往下遍歷,最後再把棧裡的節點存回結果即可,參見程式碼如下:

解法二:

class Solution {
public:
    vector<string> findItinerary(vector<pair<string, string>> tickets) {
        vector<string> res;
        stack<string> st{{"JFK"}};
        unordered_map<string, multiset<string>> m;
        for (auto t : tickets) {
            m[t.first].insert(t.second);
        }
        while (!st.empty()) {
            string t = st.top(); 
            if (m[t].empty()) {
                res.insert(res.begin(), t);
                st.pop();
            } else {
                st.push(*m[t].begin());
                m[t].erase(m[t].begin());
            }
        }
        return res;
    }
};

類似題目:

參考資料: