332. 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 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.

分析:

题目确定了至少有一条valid的行程(不存在分支情况,一定有相同的最终目的地),而且对于多条valid的行程,要选取字母顺序较小的一条。重构的行程地点一定是有序的,
所以,使用深度优先搜索,根据departure找到arrivals集合,并利用PriorityQueue对本航段的arrivals进行字母顺序排列,再将排列后的元素顺序取出作为departure,继续DFS,然后一层一层从内而外地将起点departure放入path的首位。

 1 public class Solution {
 2     Map<String, PriorityQueue<String>> flights = new HashMap();
 3     LinkedList<String> path = new LinkedList();
 4     public List<String> findItinerary(String[][] tickets) {
 5         for (String[] oneway: tickets) {
 6             flights.putIfAbsent(oneway[0], new PriorityQueue());
 7             flights.get(oneway[0]).add(oneway[1]);
 8         }
 9         dfs("JFK");
10         return path;
11     }
12     public void dfs(String departure) {
13         PriorityQueue<String> arrivals = flights.get(departure);
14         while (arrivals != null && !arrivals.isEmpty()) dfs(arrivals.poll());
15         path.addFirst(departure);
16     }
17 }

 

posted @ 2016-10-17 09:40  北叶青藤  阅读(263)  评论(0编辑  收藏  举报