leetcode 332. Reconstruct Itinerary BFS多叉树的最小字典序

来源:互联网 发布:中信淘宝v卡积分规则 编辑:程序博客网 时间:2024/05/18 00:52

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深度优先遍历的应用,不
过要注意的是这里的使用了优先队列来实现字典序的比较,注意这里是倒序收集节点信息的!!!

代码如下:

import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.PriorityQueue;/* * 一个简单的DFS写的还是有有问题,需要急需刷第二遍leetcode * */public class Solution{    Map<String, PriorityQueue<String>>  map= new HashMap<>();    List<String> res = new ArrayList<>();    public List<String> findItinerary(String[][] tickets)     {        if(tickets==null || tickets.length<=0)            return res;        for(int i=0;i<tickets.length;i++)        {            if(map.containsKey(tickets[i][0])==false)            {                PriorityQueue<String> one=new PriorityQueue<>();                map.put(tickets[i][0], one);            }            map.get(tickets[i][0]).add(tickets[i][1]);        }        dfs("JFK");                    Collections.reverse(res);        return res;    }    public void dfs(String key)     {        if(map.containsKey(key)==false)        {            res.add(key);            return ;        }else         {            PriorityQueue<String> one=map.get(key);            while(one.isEmpty()==false)                dfs(one.poll());            res.add(key);        }    }     public static void main(String[] args)     {        Solution solution=new Solution();        String[][] tickets={{"JFK","KUL"},{"JFK","NRT"},{"NRT","JFK"}};        solution.findItinerary(tickets);     }}
原创粉丝点击