题目
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.
解题思路
初看这道题觉得是拓扑排序问题,但是踩过坑后就知道,这是求欧拉路径的问题。而这道题对所求的欧拉路径还添加了一个限制:必须以字典序从小到大输出遍历的结点。
采用贪心的算法,用
N
个小顶堆存储每个结点指向的结点(JFK
结点开始进行 DFS
,每次都对字典序最小的结点进行搜索。当搜索到最后一个结点 E
时,说明已经产生了从 JFK
到 E
的一条路径,则在最后的结果中这条路径肯定是存在的,而对剩下没有搜索到的路径,肯定可以从这条路径上的某个结点扩展出去后搜索到,因此自然就想到要回溯。所以,我们每次到达一条路径的最后结点时,就把这个结点 push_back
进结果集合中,然后回溯到上一个结点继续 DFS
,当 DFS
把所有路径都遍历完毕后,结果结合中的结点是按倒序的方式排列的,我们只需要把结果集合反转就可以了。
c++ 代码实现
class Solution {
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
unordered_map<string, priority_queue<string, vector<string>, greater<string> > > G;
vector<string> rst;
for (int i = 0; i < tickets.size(); ++i) {
G[tickets[i].first].push(tickets[i].second);
}
DFS("JFK", G, rst);
reverse(rst.begin(), rst.end());
return rst;
}
void DFS(string node, unordered_map<string, priority_queue<string, vector<string>, greater<string> > >& G, vector<string>& rst) {
while (!G[node].empty()) {
string cur = G[node].top();
G[node].pop();
DFS(cur, G, rst);
}
rst.push_back(node);
}
};