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);
    }
     
}
posted @ 2019-07-10 15:08  哇呀呀..生气啦~  阅读(125)  评论(0编辑  收藏  举报