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.
思路:刚开始用DFS,TLE,后来发现是求欧拉路径,如果不是要求大小顺序的话,不用heap,直接用个Set就好了
http://blog.csdn.net/stillxjy/article/details/51956183
https://discuss.leetcode.com/topic/36383/share-my-solution
import java.util.*;
public class Solution {
List<String> rst = new ArrayList<String>();
Map<String, PriorityQueue<String>> neighbors = new HashMap<String, PriorityQueue<String>>();
public List<String> findItinerary(String[][] tickets) {
for(String[] ticket : tickets) {
if(!neighbors.keySet().contains(ticket[0]))
neighbors.put(ticket[0], new PriorityQueue<String>());
neighbors.get(ticket[0]).add(ticket[1]);
}
dfs("JFK");
return rst;
}
// Hierholzer's algorithm
private void dfs(String src) {
PriorityQueue<String> neighbor = neighbors.get(src);
while(neighbor != null && !neighbor.isEmpty())
dfs(neighbor.poll());
rst.add(0, src);
}
}
感觉就是预先把能够到达的放到一个List里面,在dfs的时候就不需要每次遍历一遍判断
二刷:先遍历得到一条主路,但是不立马把结果放到rst里面,而是放到stack里面(因为可以会有环),然后主路遍历到头了,就开始从stack里面pop出来,当后退到有环路的路口点时,就不pop stack了,转而继续把值push到stack里。这样就实现了先把环里面的数先输出
import java.util.*;
public class Solution {
public List<String> findItinerary(String[][] tickets) {
List<String> rst = new ArrayList<String>();
Map<String, PriorityQueue<String>> neighbors = new HashMap<String, PriorityQueue<String>>();
for(String[] ticket : tickets) {
if(!neighbors.keySet().contains(ticket[0]))
neighbors.put(ticket[0], new PriorityQueue<String>());
neighbors.get(ticket[0]).add(ticket[1]);
}
Stack<String> stack = new Stack<String>();
stack.add("JFK");
while(!stack.isEmpty()) {
String src = stack.peek();
if(neighbors.get(src)!=null && !neighbors.get(src).isEmpty()) {
stack.push(neighbors.get(src).remove());
} else {
rst.add(0, stack.pop());
}
}
return rst;
}
}
Python
class Solution:
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
from collections import defaultdict
st,res=['JFK'],[]
adj=defaultdict(list)
for s,t in tickets: adj[s].append(t)
for s in adj: adj[s].sort(reverse=True)
while st:
if adj[st[-1]]:
st.append(adj[st[-1]].pop())
else:
res.append(st.pop())
while st: res.append(st.pop())
return res[::-1]
s=Solution()
print(s.findItinerary([["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]))