[LeetCode][JavaScript]Reconstruct Itinerary

Reconstruct Itinerary

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.

https://leetcode.com/problems/reconstruct-itinerary/

 

 


 

 

DFS, 从JFK开始,要经过所有的机场,如果有多个选择,去字母序小的机场。

先遍历构造地图,再把目标机场的排个序,最后DFS遍历找出结果。

 1 /**
 2  * @param {string[][]} tickets
 3  * @return {string[]}
 4  */
 5 var findItinerary = function(tickets) {
 6     var i, curr, map = {}, countNode = 0;
 7     //build graph
 8     for(i = 0; i < tickets.length; i++){
 9         curr = tickets[i];
10         if(!map[curr[0]]) map[curr[0]] = [{dest: curr[1], visited: false}];
11         else map[curr[0]].push({dest: curr[1], visited: false});
12     }
13     for(i in map){
14         map[i] = map[i].sort(sorting).slice(0);
15     }
16     return dfs("JFK", ["JFK"]);
17     
18     function sorting(a, b){
19         if(a.dest === b.dest) return 0;
20         else if(a.dest > b.dest) return 1;
21         return -1;
22     }
23     function dfs(fromNode, path){
24         if(countNode === tickets.length) return path;
25         var currNode = map[fromNode], res;
26         if(!currNode) return false;
27         for(var i = 0; i < currNode.length; i++){
28             if(currNode[i].visited) continue;
29             currNode[i].visited = true;
30             countNode++;
31             path.push(currNode[i].dest);
32             res = dfs(currNode[i].dest, path);
33             if(res) return res;
34             currNode[i].visited = false;
35             countNode--;
36             path.pop();
37         }
38         return false;
39     }
40 };

 

 

 

posted @ 2016-02-18 18:14  `Liok  阅读(519)  评论(0编辑  收藏  举报