题目:
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:
- 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"]
. - All airports are represented by three capital letters (IATA code).
- You may assume all tickets 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.
思路:
这道题目的特殊之处在于需要使用bottom up的DFS,就是路径是反向从最底层网上得出的。我们首先将所有的机票用哈希表给保存起来,最后就是要找一条路径将机票用完,并且如果有多条路径,就找字典序最小的。我们定义的数据结构是multiset<string>来表示哈希表的value,这是因为一方面里面可能会有重复字符串,另一方面multiset自动排序,方便我们有序的读取数据。
接下来我们就从“JFK”机场出发,按照字典序从小到大选取与其连接的地方,从下一个地点再递归的进行搜索,直到没有和某地点相连的机票了。此时我们就到达了最底层,然后往上返回路径即可。
感觉这个代码还是有点不太好理解,欢迎大家在留言中讨论。
代码:
class Solution {
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
if(tickets.size() == 0) {
return result;
}
unordered_map<string, multiset<string>> hash;
for(auto val : tickets) {
hash[val.first].insert(val.second);
}
stack<string> st; // stores the current possible departing airports
st.push("JFK");
while(!st.empty()) {
string s = st.top();
if(hash.find(s) != hash.end()) {
st.push(*hash[s].begin());
hash[s].erase(hash[s].begin());
if(hash[s].size() == 0) {
hash.erase(s);
}
}
else { // cannot go to the next airport, so of course it will be the first departure airport
result.push_back(s);
st.pop();
}
}
reverse(result.begin(), result.end());
return result;
}
private:
vector<string> result;
};