Reconstruct Itinerary
来源:互联网 发布:js select disabled 编辑:程序博客网 时间:2024/05/17 14:24
问题来源
问题描述
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.
问题分析
显然,这是一道与有向图路径相关的题目。题目的大意是从给出的一堆有向边组合而成的图中找出一条从顶点JFK
到达其他顶点的字母序最小的路径。我们暂时不管字母序的问题,仅考虑如何选取一条路径。显然,DFS是一个较优的选择。以JFK为起点深度遍历整张图,注意到图中是有环的,所以我们还需做多的一步操作便是删除已遍历的边避免进入死循环。至于字母序的问题,我们只需要要每个结点的子结点按照字典序排好,遍历时从字典序最小的结点开始遍历即可。每次将当前结点的子结点遍历完成后再将当前结点压入路径数组中,最后将路径数组反转即可得到答案。
解决代码
class Solution { public: vector<string> findItinerary(vector<pair<string, string>> tickets) { map<string, multiset<string>> edges; for (auto loc : tickets) { edges[loc.first].insert(loc.second); } vector<string> res; if (tickets.size() == 0) return res; dfs(res, "JFK", edges); reverse(res.begin(), res.end()); return res; } void dfs(std::vector<string>& r, string loc, map<string, multiset<string>> & edges) { while (edges[loc].size()) { auto tmp = *(edges[loc].begin()); edges[loc].erase(edges[loc].begin()); dfs(r, tmp, edges); } r.push_back(loc); }};
阅读全文
0 0
- Reconstruct Itinerary
- Reconstruct Itinerary
- Reconstruct Itinerary
- Reconstruct Itinerary
- Reconstruct Itinerary
- Reconstruct Itinerary
- Reconstruct Itinerary
- Reconstruct Itinerary
- Reconstruct Itinerary
- Reconstruct Itinerary
- leetcode Reconstruct Itinerary
- *[LeetCode]332. Reconstruct Itinerary
- 332. Reconstruct Itinerary
- leetcode 332. Reconstruct Itinerary
- LeetCode332. Reconstruct Itinerary
- [LeetCode 332] Reconstruct Itinerary
- 332. Reconstruct Itinerary
- LeetCode 332 : Reconstruct Itinerary
- 初学java
- EA&UML日拱一卒-活动图::14.2 Behavior StateMachines (11)
- Qt中如何解析Json数据
- NOIP2015子串题解
- 关于Win10 无法登陆破解方法
- Reconstruct Itinerary
- 智能指针
- Java面试题(三)TCP/IP协议
- String源码分析
- sqlldr的使用
- 由递归引出的斐波那契数列(暂)
- 51Nod--正整数分组--01背包问题
- SDUT 2139 图结构练习——BFS——从起始点到目标点的最短步数
- [caioj1469][后缀数组]连续重复子串