LeetCode 332. Reconstruct Itinerary

本文介绍了一种基于欧拉路径的算法,用于解决从给定的航空票中重构旅行路线的问题。该算法确保每张票仅使用一次,并且旅行始于JFK机场。通过构建有向图并利用优先队列来确保字母顺序最小,最终通过深度优先搜索获得旅行路线。

原题链接在这里:https://leetcode.com/problems/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:
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.

题解:

Eulerian path. 把这些ticket当成edge构建directed graph. 保证每条edge 只走一遍.

为了保证字母顺序,用了PriorityQueue.

然后做dfs. dfs 时注意 retrieve nodes backwards.

Time Complexity: O(n+e). Space: O(n+e).

AC Java:

 1 public class Solution {
 2     Map<String, PriorityQueue<String>> graph = new HashMap<String, PriorityQueue<String>>();
 3     public List<String> findItinerary(String[][] tickets) {
 4         List<String> res = new LinkedList<String>();
 5         if(tickets == null || tickets.length == 0 || tickets[0].length == 0){
 6             return res;
 7         }
 8         
 9         for(String [] edge : tickets){
10             if(!graph.containsKey(edge[0])){
11                 graph.put(edge[0], new PriorityQueue<String>());
12             }
13             graph.get(edge[0]).add(edge[1]);
14         }
15         
16         dfs("JFK", res);
17         return res;
18     }
19     
20     private void dfs(String s, List<String> res){
21         while(graph.containsKey(s) && !graph.get(s).isEmpty()){
22             dfs(graph.get(s).poll(), res);
23         }
24         res.add(0, s);
25     }
26 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/5309418.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值