[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; } };
相关文章推荐
- 使用CEF的JSON解析功能
- ( 译、持续更新 ) JavaScript 上分小技巧(四)
- JSP中page和pageContext的区别
- js数组常用方法汇总
- 关于JSP九大内置对象的详细信息
- javascript 练习
- JS中的Map
- javascript二维数组遍历
- javascript 定时页面跳转
- 鼠标滑过触发拉窗式JS效果
- Js中计算后台传过来map size
- Javascript自学-3
- JS字符串的相关方法
- js图片预加载
- js图片预加载
- JavaScript DOM接口
- JavaScript DOM
- sublime text3 JS语法检测插件
- JavaScript运算优先级
- JSON