332. Reconstruct Itinerary (M)

Reconstruct Itinerary (M)

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: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]

Example 2:

Input: [["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.

题意

重新安排行程,使得从"JFK"出发的航班到达所有地点,如果存在多条可行的路径,则优先走字典序较小的地点。

思路

用HashMap存储所有路径A->[B1, B2, …],并用堆来对B按照字典序排序。DFS处理:从"JFK"出发,如果当前点存在下一个可到达的点,则删除这两个点之间的边,并向下递归,处理完所有可到达的点后,将当前点加入结果序列里。DFS完成后只要将结果序列逆置即可。(逆后序遍历+贪心,类似欧拉路径)


代码实现

class Solution {
    public List<String> findItinerary(List<List<String>> tickets) {
        Map<String, Queue<String>> hash = new HashMap<>();
        for (List<String> list : tickets) {
            hash.putIfAbsent(list.get(0), new PriorityQueue<>());
            hash.get(list.get(0)).offer(list.get(1));
        }

        List<String> ans = new ArrayList<>();
        dfs(hash, ans, "JFK");
        Collections.reverse(ans);
        return ans;
    }

    private void dfs(Map<String, Queue<String>> hash, List<String> ans, String cur) {
        if (!hash.containsKey(cur)) {
            ans.add(cur);
            return;
        }
        Queue<String> q = hash.get(cur);
        while (!q.isEmpty()) {
            String s = q.poll();
            dfs(hash, ans, s);
        }
        hash.remove(cur);
        ans.add(cur);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值