332-Reconstruct Itinerary

Description

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:

Input: tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]

Example 2:

Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order.

问题描述

给定飞机票列表, 每张票由出发地和目的地的对来表示, 即[from, to], 按顺序重构旅游线路。所有的这些票都属于一个由JFK出发的人。因此, 线路必须以JFK开始

注意

  1. 如果有多个有效的线路, 返回字符串表示下字典序最小的线路。例如, 线路[“JFK”, “LGA”]比[“JFK”, “LGB”]有更小的字典序
  2. 所有的飞机场由三个大写字母表示
  3. 所有机票至少形成一个有效的线路

问题分析

这一题涉及到了欧拉路径, 如果不太了解欧拉路径, 可以看看维基:
https://en.wikipedia.org/wiki/Eulerian_path


解法

class Solution {
    Map<String,PriorityQueue<String>> map = null;
    LinkedList<String> result = new LinkedList();

    public List<String> findItinerary(String[][] tickets) {
        map = getMap(tickets);

        makeItinerary("JFK");

        return result;
    }
    private void makeItinerary(String from){
        PriorityQueue<String> tos = map.get(from);

        while(tos !=null && !tos.isEmpty()) makeItinerary(tos.poll());

        result.addFirst(from);       
    } 
    private Map<String,PriorityQueue<String>> getMap(String[][] tickets){
        Map<String,PriorityQueue<String>> map = new HashMap<String,PriorityQueue<String>>();

        for(String[] ticket: tickets){
            String from = ticket[0];
            String to = ticket[1];
            if(!map.containsKey(from))  map.put(from,new PriorityQueue<String>());
            map.get(from).offer(to);
        }     

        return map;
    }
}

你可能感兴趣的:(算法与数据结构)