您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Reconstruct Itinerary

2016-02-18 18:14 736 查看

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:

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.

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

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

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

/**
* @param {string[][]} tickets
* @return {string[]}
*/
var findItinerary = function(tickets) {
var i, curr, map = {}, countNode = 0;
//build graph
for(i = 0; i < tickets.length; i++){
curr = tickets[i];
if(!map[curr[0]]) map[curr[0]] = [{dest: curr[1], visited: false}];
else map[curr[0]].push({dest: curr[1], visited: false});
}
for(i in map){
map[i] = map[i].sort(sorting).slice(0);
}
return dfs("JFK", ["JFK"]);

function sorting(a, b){
if(a.dest === b.dest) return 0;
else if(a.dest > b.dest) return 1;
return -1;
}
function dfs(fromNode, path){
if(countNode === tickets.length) return path;
var currNode = map[fromNode], res;
if(!currNode) return false;
for(var i = 0; i < currNode.length; i++){
if(currNode[i].visited) continue;
currNode[i].visited = true;
countNode++;
path.push(currNode[i].dest);
res = dfs(currNode[i].dest, path);
if(res) return res;
currNode[i].visited = false;
countNode--;
path.pop();
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: