LeetCode 332. Reconstruct Itinerary重新安排行程 (C++/Java)
题目:
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:
Input:[["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output:["JFK", "MUC", "LHR", "SFO", "SJC"]
Example 2:
Input:[["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output:["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is["JFK","SFO","ATL","JFK","ATL","SFO"].
But it is larger in lexical order.
分析:
给定一个机票的字符串二维数组 [from, to],子数组中的两个成员分别表示飞机出发和降落的机场地点,对该行程进行重新规划排序。所有这些机票都属于一个从JFK(肯尼迪国际机场)出发的先生,所以该行程必须从 JFK 出发。
可以将题目理解为一个有向图,飞机票当成图的边,最后求的是结点的顺序,实际上是求一个欧拉回路。

这里我们使用Hierholzer算法求解此问题。
正常来说我们应该先求出度为奇数的点,不过由于这道题告知要从“JFK”开始,所以我们可以直接从JFK开始搜索。
DFS(u):
while(u存在未被访问过的边e(u, v))
标记边e(u, v)已被访问
DFS(v)
END
将点u添加到路径集中
还是以上面的为例,从JFK开始,存在未被访问的边(1,3),我们在这个选择3,也就是通往SFO的边(注意此题要求应该是选择字符排序小的点,这里只是模拟一下求解欧拉回路的过程),然后我们将3这条边标记以访问。
然后从SFO开始,存在为被访问的边(4),我们选择4这条边,到达了ATL这个点,同样的4也被标记访问过了。
ATL存在未被访问的边(5,2),我们选择5这条边,到达了SFO这个点,5也被标记访问过。
SFO已经不存在未被访问的边了(4已经被标记访问过了),所以我们将SFO加入到路径集中[SFO],并返回上次访问的点。
此时ATL中还存在2这条边未被访问,我们选择2这条边,到达了JFK这个点,2也标记访问过。
JFK中1还未访问,我们选择1这条边,到达了ATL这个点,注意此时所有的边都已经访问过了,ATL没有边可以继续访问了,我们将ATL加入路径集[SFO,ATL],返回上次访问的点。
此时JFK也没有边访问了,我们将JFK加入[SFO,ATL,JFK]
同理ATL也没有可访问的边了,将ATL加入[SFO,ATL,JFK,ATL]
返回到SFO,也没有边可以访问了,将SFO加入[SFO,ATL,JFK,ATL,SFO]
最后我们回到了出发点JFK,1,3都已被标记访问过,将JFK加入到路径集中得[SFO,ATL,JFK,ATL,SFO,JFK],最后将结果集中数据反转一下即可得到所求得欧拉路径。也就是JFK->SFO->ATL->JFK->ATL->SFO
不过注意由于题中要求字符自然排序最小,所以我们在选择边时,要按照顺序选在下一个访问的结点。例如从JFK开始有通向SFO和ATL两个边,我们选择通往ATL的边,依照这样的规则我们可以得到结果
["JFK","ATL","JFK","SFO","ATL","SFO"]

小技巧:在保存机票起点和终点时,我们可以使用有限队列存储边,优先访问字符小的边。
程序:
C++
class Solution {
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
for(int i = 0; i < tickets.size(); ++i){
if(map.find(tickets[i][0]) == map.end()){
priority_queue <string, vector<string>, cmp> q;
q.push(tickets[i][1]);
map[tickets[i][0]] = q;
}
else{
map[tickets[i][0]].push(tickets[i][1]);
}
}
findPath("JFK");
reverse(res.begin(), res.end());
return res;
}
void findPath(string begin){
while(map.find(begin) != map.end() && map[begin].size() != 0){
string next = map[begin].top();
map[begin].pop();
findPath(next);
}
res.push_back(begin);
}
private:
struct cmp
{
bool operator() (string a, string b)
{
return a > b;
}
};
vector<string> res;
unordered_map<string, priority_queue <string, vector<string>, cmp>> map;
};
Java
class Solution {
public List<String> findItinerary(List<List<String>> tickets) {
for(List<String> pair:tickets){
String key = pair.get(0);
String value = pair.get(1);
if(!map.containsKey(key)){
PriorityQueue<String> p = new PriorityQueue<>();
p.add(value);
map.put(key, p);
}
else{
map.get(key).add(value);
}
}
getPath("JFK");
return res;
}
private void getPath(String begin){
while(map.containsKey(begin) && map.get(begin).size() != 0){
getPath(map.get(begin).poll());
}
res.add(0, begin);
}
private List<String> res = new ArrayList<>();
private Map<String, PriorityQueue<String>> map = new HashMap<>();
}
LeetCode 332. Reconstruct Itinerary重新安排行程 (C++/Java)的更多相关文章
- [leetcode]332. Reconstruct Itinerary
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], r ...
- 【LeetCode】332. Reconstruct Itinerary 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 后序遍历 相似题目 参考资料 日期 题目地址:htt ...
- 【LeetCode】Reconstruct Itinerary(332)
1. Description Given a list of airline tickets represented by pairs of departure and arrival airport ...
- 【LeetCode】332. Reconstruct Itinerary
题目: Given a list of airline tickets represented by pairs of departure and arrival airports [from, to ...
- 332. Reconstruct Itinerary (leetcode)
1. build the graph and then dfs -- graph <String, List<String>>, (the value is sorted a ...
- 332 Reconstruct Itinerary 重建行程单
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], r ...
- 332. Reconstruct Itinerary
class Solution { public: vector<string> path; unordered_map<string, multiset<string>& ...
- Java实现 LeetCode 332 重新安排行程
332. 重新安排行程 给定一个机票的字符串二维数组 [from, to],子数组中的两个成员分别表示飞机出发和降落的机场地点,对该行程进行重新规划排序.所有这些机票都属于一个从JFK(肯尼迪国际机场 ...
- Leetcode 332.重新安排行程
重新安排行程 给定一个机票的字符串二维数组[from, to],子数组中的两个成员分别表示飞机出发和降落的机场地点,对该行程进行重新规划排序.所有这些机票都属于一个从JFK(肯尼迪国际机场)出发的先生 ...
- [Swift]LeetCode332. 重新安排行程 | Reconstruct Itinerary
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], r ...
随机推荐
- mysql入门操作(部分操作,不为完全格式)
查询数据库在电脑中绝对路径: show variables like '%datadir%'; 设置字符集 set names gbk; 导入数据库 source 绝对路径 eg: source D: ...
- 使用 Gradio 的“热重载”模式快速开发 AI 应用
在这篇文章中,我将展示如何利用 Gradio 的热重载模式快速构建一个功能齐全的 AI 应用.但在进入正题之前,让我们先了解一下什么是重载模式以及 Gradio 为什么要采用自定义的自动重载逻辑.如果 ...
- 阿里巴巴云原生 etcd 服务集群管控优化实践
简介: 这些年,阿里云原生 etcd 服务发生了翻天覆地的变化,这篇文章主要分享一下 etcd 服务在面对业务量大规模增长下遇到的问题以及我们是如何解决的,希望对读者了解 etcd 的使用和管控运维提 ...
- 一文读懂容器存储接口 CSI
简介: 在<一文读懂 K8s 持久化存储流程>一文我们重点介绍了 K8s 内部的存储流程,以及 PV.PVC.StorageClass.Kubelet 等之间的调用关系.接下来本文将将重点 ...
- OLAP系列之分析型数据库clickhouse集群部署(二)
一.环境准备 IP 配置 clickhouse版本 zookeeper版本 myid 192.168.12.88 Centos 7.9 4核8G 22.8.20.11 3.7.1 3 192.168. ...
- 通过Google浏览器Cookie文件获取cookie信息,80以上版本有效
public class ReadCookie { /// <summary> /// </summary> /// <param name="hostName ...
- C语言程序设计-笔记6-数组
C语言程序设计-笔记6-数组 例7-1 输出所有大于平均值的数.输入n个整数(1 ),计算这些数的平均值,再输出所有大于平均值的数. #include<stdio.h> int main ...
- vue-公共组件的注册
注册公共组件,在每个需要的页面直接输入文件名(<g-table/>)即可引用该组件 步骤: 1.新建components/global文件夹,以及components/global/g-t ...
- P10118 『STA - R4』And
P10118 『STA - R4』And 题意:给定 A,B,求 \(\sum y - x\),其中 x,y 满足: x < y x + y = A x & y = B 对于加运算和与运 ...
- ubuntu_24.04 Noble LTS安装docker desktop启动无窗口及引擎启动失败的解决方法
ubuntu_24.04 LTS安装docker desktop启动无窗口及引擎启动失败的解决方法 1. 安装docker desktop后启动无窗口 现象: 执行sudo apt install . ...