descrption
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.解题思路
这道题是给出多张飞机票,让我们利用全部飞机票找出一个路线。从JKF出发,如果从一个地方起飞有多张机票,那么就根据到达地名称字典序从小到大选择最小的那个。既然要有顺序,那么我们就用multiset来存储一个出发地可以直接飞到的到达地,这样就可以有顺序的选择字典序最小的到达地了。用map来维护出发地与它可以直飞到的到达地的关系。这个题目至少有一个合法的路径,那么我们将每个地点看做一个node,一定会有一条路线覆盖了每一条边并且不会重复。我们从“JFK”开始做DFS,直到用完了所有的边,开始回溯时将节点依次加到路径中。最后要得到的路线结果与这条路径相反,reverse得到的路径就可以得到结果了。代码如下
class Solution {
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
map<string, multiset<string>> ticket;
vector<string> route;
for (auto t : tickets){
ticket[t.first].insert(t.second);
}
dfs(ticket, route, "JFK");
reverse(route.begin(), route.end());
return route;
}
void dfs(map<string, multiset<string>> &ticket, vector<string> &route, string begin){
while(ticket[begin].size()){
auto adj = ticket[begin].begin();
ticket[begin].erase(adj);
dfs(ticket, route, *adj);
}
route.push_back(begin);
}
};
原题地址
如有错误请指出,谢谢!