作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/reconstruct-itinerary/description/

题目描述

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.

题目大意

重新安排行程,使得给出的所有航班都得经过一次。如果出现多条可行的路径,那么优先选择的字典序最小的航班路径。出发点一定是JFK,而且题目保证了最少有一个可行的遍历路径。

解题方法

后序遍历

感觉是我自己太菜鸡了,看到花花神一般的解法,感觉自己永远不可能想出来的。

这道题的本质是计算一个最"小"的欧拉路径(Eulerian path)。对于一个节点(当然先从JFK开始),贪心地访问最小的邻居,访问过的边全部删除。当碰到死路的时候就回溯到最近一个还有出路的节点,然后把回溯的路径放到最后去访问,这个过程和后序遍历的一样。1. 如果子节点没有死路(每个节点都只左子树),前序遍历便是欧拉路径。2. 如果子节点1是死路,子节点2完成了遍历,那么子节点2先要被访问。1,2都和后序遍历的顺序正好相反。

其中,如果碰到死路,而没有把所有的边都走过一遍的话,就说明这种走法不满足itinerary,需要沿着树根向上找到最近的一个有其他路可以走的节点N,把新的路走一遍。因为题目保证一定存在一条满足要求的itinerary路径,那么一条这样的死路,一定会相对的在这个节点N上存在另一条路,这条路存在一个回到该节点N的环。先把这个环走过之后再去走这条死路,就可以保证把以N为树根的这个路径上的所有点都走到。

首先肯定是要把路径保存成链表法表示的图的。然后对每个顶点的所有邻接顶点进行排序,这样我们每次都优先选择字典序最小的那个顶点作为下次遍历的节点。我们做了后序遍历即可。最后还要把后序遍历的结果再翻转,才是从根节点出发到每个位置的路径。

最坏时间复杂度是O(VlogV),空间复杂度是O(E).

class Solution(object):
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
graph = collections.defaultdict(list)
for frm, to in tickets:
graph[frm].append(to)
for frm, tos in graph.items():
tos.sort(reverse=True)
res = []
self.dfs(graph, "JFK", res)
return res[::-1] def dfs(self, graph, source, res):
while graph[source]:
v = graph[source].pop()
self.dfs(graph, v, res)
res.append(source)

相似题目

参考资料

https://www.youtube.com/watch?v=4udFSOWQpdg

日期

2018 年 10 月 30 日 —— 啊,十月过完了

【LeetCode】332. Reconstruct Itinerary 解题报告(Python)的更多相关文章

  1. [leetcode]332. Reconstruct Itinerary

    Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], r ...

  2. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  3. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  4. 【LeetCode】Permutations II 解题报告

    [题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...

  5. 【LeetCode】Island Perimeter 解题报告

    [LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...

  6. 【LeetCode】01 Matrix 解题报告

    [LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...

  7. 【LeetCode】Largest Number 解题报告

    [LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...

  8. 【LeetCode】Gas Station 解题报告

    [LeetCode]Gas Station 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/gas-station/#/descr ...

  9. LeetCode: Unique Paths II 解题报告

    Unique Paths II Total Accepted: 31019 Total Submissions: 110866My Submissions Question Solution  Fol ...

随机推荐

  1. Redis—怎么查看Linux有没有安装Redis,如何启动Redis

    1.检测是否有安装redis-cli和redis-server [root@localhost bin]# whereis redis-cli redis-cli: /usr/bin/redis-cl ...

  2. Hadoop入门 完全分布式运行模式-集群配置

    目录 集群配置 集群部署规划 配置文件说明 配置集群 群起集群 1 配置workers 2 启动集群 总结 3 集群基本测试 上传文件到集群 查看数据真实存储路径 下载 执行wordcount程序 配 ...

  3. 17. yum

    https://www.linuxidc.com/Linux/2015-04/116331.htm

  4. VSCode+Maven+Hadoop开发环境搭建

    在Maven插件的帮助下,VSCode写Java其实非常方便.这一讲我们介绍如何借助maven用VScode搭建Hadoop开发环境. 1.Java环境安装 首先我们需要搭建好Java开发环境.我们需 ...

  5. 【leetcode】797. All Paths From Source to Target

    Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths fro ...

  6. Output of C++ Program | Set 11

    Predict the output of following C++ programs. Question 1 1 #include<iostream> 2 using namespac ...

  7. 初始化Linux数据盘、磁盘分区、挂载磁盘(fdisk)

    1.操作场景 2.前提条件 3.划分分区并挂载磁盘 4.设置开机自动挂载磁盘分区 1.操作场景 本文以云服务器的操作系统为"CentOS 7.4 64位"为例,采用fdisk分区工 ...

  8. 【编程思想】【设计模式】【行为模式Behavioral】中介者模式Mediator

    Python版 https://github.com/faif/python-patterns/blob/master/behavioral/mediator.py #!/usr/bin/env py ...

  9. 阿里云esc 登录时的相关提示

    1. 如果该ecs 未绑定密钥对,可以通过常规的用户名密码登录 2. 如果该 ecs 绑定了密钥对,则需要通过私钥进行登录 3. 如果使用 比如 securityCRT 登录时报 " A p ...

  10. 使用beanFactory工厂实例化容器的方式实现单例模式

    //配置文件bean.properties(注意书写顺序) accountService=com.itheima.service.impl.AccountServiceImplaccountDao=c ...