zoukankan      html  css  js  c++  java
  • 332. Reconstruct Itinerary


    July-10-2019

    这个题,有点像course schedule,然后初始点是JFK已经告诉你了。用node, list来建图,正常DFS就行。 这个2个需要注意:

    • 要求排序,LIST需要排序,所以用了PQ
    • 有[JFK, PDX][JFK, DUB][PDX, NRT]这样,DUB放在最后,所以从JFK开始的DFS,要遍历JFK的整个PQ。
    class Solution {
        
        private static final String START_CITY = "JFK";
        
        public List<String> findItinerary(List<List<String>> tickets) {
            
            if (tickets == null || tickets.isEmpty()) return Arrays.asList(START_CITY);
            List<String> res = new ArrayList<>();
            
            Map<String, PriorityQueue<String>> graph = new HashMap<>();
            tickets.stream().forEach(path -> {
                String from = path.get(0);
                String to = path.get(1);
                if (!graph.containsKey(from)) {
                    graph.put(from, new PriorityQueue<String>());
                }
                graph.get(from).add(to);
            });
            
            dfs(graph, START_CITY , res);
            
            return res;
        }
        
        public void dfs(Map<String, PriorityQueue<String>> graph, String city, List<String> res) {
            while (graph.containsKey(city) && !graph.get(city).isEmpty()) {
                dfs(graph, graph.get(city).poll(), res);
            }
    
            res.add(0, city);
        }
         
    }
    
  • 相关阅读:
    2014华为员工年终奖及年薪盘点
    Gradle命令行黑魔法
    委托的那些事
    动态代理
    音乐播放
    Eclipse plugin web site 发布和版本更新
    JavaScript—之对象参数的引用传递
    Bootstrap 3 How-To #1 下载与配置
    代码审计和漏洞挖掘的思路
    核心C#
  • 原文地址:https://www.cnblogs.com/reboot329/p/11164055.html
Copyright © 2011-2022 走看看