题意

给N个单词表示N个点,和N-1个单词对,表示可以走的路径,求字典序最小的总路径。

首先说下这么暴力DFS能过。暴力的我都不敢写= =

class Solution {
public:
vector<string> findItinerary(vector<vector<string> >& tickets) {
map<string, vector<string> > mp; for (int i = 0; i < tickets.size(); i++) {
string from = tickets[i][0];
string to = tickets[i][1];
if (mp.find(from) == mp.end()) {
vector<string> v;
v.push_back(to);
mp[from] = v;
} else {
mp[from].push_back(to);
}
}
for (map<string, vector<string> >::iterator iter = mp.begin(); iter != mp.end(); iter++) {
sort(iter->second.begin(), iter->second.end());
}
vector<string> res;
string cur = "JFK";
res.push_back(cur);
dfs(cur, mp, res, tickets.size());
return res;
} bool dfs(string cur, map<string, vector<string> > &mp, vector<string> &res, int n) {
if (res.size() == n + 1) return true;
if (mp.find(cur) == mp.end()) return false;
if (mp[cur].size() == 0) return false;
for (int i = 0; i < mp[cur].size(); i++) {
string nxt = mp[cur][i];
res.push_back(nxt);
mp[cur].erase(mp[cur].begin() + i);
if (dfs(nxt, mp, res, n)) return true;
mp[cur].insert(mp[cur].begin() + i, nxt);
res.pop_back();
}
return false;
}
};

然后说正解。

如果把每一个字符串当做一个点,每一个字符串对就是一条有向边。那么这么题目就是要求输出最小字典序的欧拉路径。

以下参考 https://www.cnblogs.com/TEoS/p/11376707.html

什么是欧拉路径?欧拉路径就是一条能够不重不漏地经过图上的每一条边的路径,即小学奥数中的一笔画问题。而若这条路径的起点和终点相同,则将这条路径称为欧拉回路。

如何判断一个图是否有欧拉路径呢?显然,与一笔画问题相同,一个图有欧拉路径需要以下几个条件:

  • 首先,这是一个连通图
  • 若是无向图,则这个图的度数为奇数的点的个数必须是0或2;若是有向图,则要么所有点的入度和出度相等,要么有且只有两个点的入度分别比出度大1和少1

上面这两个条件很好证明。查找欧拉路径前,必须先保证该图满足以上两个条件,否则直接判误即可。

查找欧拉路径的算法有Fluery算法和Hierholzer算法。下面介绍一下Hierholzer算法。

算法流程:

  1. 对于无向图,判断度数为奇数的点的个数,若为0,则设任意一点为起点,若为2,则从这2个点中任取一个作为起点;对于有向图,判断入度和出度不同的点的个数,若为0,则设任意一点为起点,若为2,则设入度比出度小1的点为起点,另一点为终点。具体起点的选择要视题目要求而定。
  2. 从起点开始进行递归:对于当前节点x,扫描与x相连的所有边,当扫描到一条(x,y)时,删除该边,并递归y。扫描完所有边后,将x加入答案队列。
  3. 倒序输出答案队列。(因为这里是倒序输出,我们可以用栈来存储答案,当然用双端队列也可以)

我画图理解一下这个算法,一个欧拉路径其实都是这个样子的

就是从起点到终点的路径上画几个圈。

举两个具体的例子

path = []

A --> B --> C 因为C没有再相连的边 所以把C加入路径 path=[C]

    --> D --> B 因为B没有再相连的边 所以把B加入路径 path=[C, B]

      D  path=[C, B, D]

   B path=[C, B, D, B]

A path=[C, B, D, B, A]

path = []

A --> B --> C --> B --> D 因为D没有再相连的边 所以把D加入路径 path=[D]

          B path=[D, B]

      C path=[D, B, C]

   B path=[D, B, C, B]

A path=[D, B, C, B, A]

所以无论先遍历的那一条边都能得出正确的欧拉路径,既然题目要求字典序,那么每次选择最小字符串先处理即可。

代码

class Solution {
public:
vector<string> findItinerary(vector<vector<string> >& tickets) {
map<string, priority_queue<string,vector<string>,greater<string> > > mp; for (int i = 0; i < tickets.size(); i++) {
string from = tickets[i][0];
string to = tickets[i][1];
if (mp.find(from) == mp.end()) {
priority_queue<string,vector<string>,greater<string> > q;
q.push(to);
mp[from] = q;
} else {
mp[from].push(to);
}
}
vector<string> res;
string cur = "JFK";
dfs(cur, mp, res);
reverse(res.begin(), res.end());
return res;
} void dfs(string cur, map<string, priority_queue<string,vector<string>,greater<string> > > &mp, vector<string> &res) {
while(mp[cur].size()) {
string nxt = mp[cur].top();
mp[cur].pop();
dfs(nxt, mp, res);
}
res.push_back(cur);
}
};

LeetCode 332. Reconstruct Itinerary 最小欧拉路径的更多相关文章

  1. [leetcode]332. Reconstruct Itinerary

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

  2. 【LeetCode】332. Reconstruct Itinerary 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 后序遍历 相似题目 参考资料 日期 题目地址:htt ...

  3. 【LeetCode】Reconstruct Itinerary(332)

    1. Description Given a list of airline tickets represented by pairs of departure and arrival airport ...

  4. 【LeetCode】332. Reconstruct Itinerary

    题目: Given a list of airline tickets represented by pairs of departure and arrival airports [from, to ...

  5. 332. Reconstruct Itinerary (leetcode)

    1. build the graph and then dfs -- graph <String, List<String>>,  (the value is sorted a ...

  6. 332 Reconstruct Itinerary 重建行程单

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

  7. 332. Reconstruct Itinerary

    class Solution { public: vector<string> path; unordered_map<string, multiset<string>& ...

  8. [LeetCode] Reconstruct Itinerary 重建行程单

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

  9. LeetCode Reconstruct Itinerary

    原题链接在这里:https://leetcode.com/problems/reconstruct-itinerary/ 题目: Given a list of airline tickets rep ...

  10. [Swift]LeetCode332. 重新安排行程 | Reconstruct Itinerary

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

随机推荐

  1. golang 实现的零依赖、高性能、并发 mysqldump 工具。

    mysqldump golang 中实现的零依赖.高性能.并发 mysqldump 工具. 项目地址: https://github.com/dengjiawen8955/mysqldump/blob ...

  2. Linux安装软件命令详解

    Linux安装软件命令详解 目录 一.deb包的简介.安装及卸载步骤 二.rpm包的简介.安装及卸载步骤 三.AppImage包的简介.执行步骤 四.tar.gz.tar.bz2源代码包的简介.安装及 ...

  3. 神经网络之卷积篇:详解计算机视觉(Computer vision)

    详解计算机视觉 计算机视觉是一个飞速发展的一个领域,这多亏了深度学习.深度学习与计算机视觉可以帮助汽车,查明周围的行人和汽车,并帮助汽车避开它们.还使得人脸识别技术变得更加效率和精准,即将能够体验到或 ...

  4. Jmeter函数助手41-unescapeHtml

    unescapeHtml函数用于将HTML转义过的字符串反转义为Unicode字符串. String to unescape:填入字符 1.escapeHtml函数是将字符进行HTML转义,unesc ...

  5. 使用Java对稀疏数组的压缩与还原

    稀疏矩阵的压缩与还原 稀疏数组中元素个数很少或者有大量的重复值,如果直接保存保存,会浪费很多空间,这时,就可以考虑对数组进行压缩存储. 先定义一个稀疏数组 //创建一个二维数组 11 * 11 int ...

  6. 《Python数据可视化之matplotlib实践》 源码 第二篇 精进 第七章

    图   7.1   import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np mpl.rcParams[& ...

  7. 连接huggingface.co报错:(MaxRetryError("SOCKSHTTPSConnectionPool(host='huggingface.co', port=443) (SSLEOFError(8, '[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1007)

    参考: https://blog.csdn.net/shizheng_Li/article/details/132942548 https://blog.csdn.net/weixin_4220944 ...

  8. 国产软件如何让人再次失望——!20824 mindspore1.3.0gpu version can not compile from source code, because openmpi source code has bug

    如题,该PR地址: https://gitee.com/mindspore/mindspore/pulls/20824#note_7053720 What type of PR is this? Un ...

  9. 从baselines库的common/vec_env/vec_normalize.py看reinforcement learning算法中的reward shape方法

    参考前文:https://www.cnblogs.com/devilmaycry812839668/p/15889282.html 2.  REINFORCE算法实际代码中为什么会对一个episode ...

  10. Java实现微信登录(网页授权)

    1.背景 实际开发中,使用第三方登录是非常常见的业务... 这样可以大提高用户体验,没必要一来就要注册,或者登录之类的... 并且开发一个登录或者注册严格来说也是非常麻烦的(各种防止攻击.机器操作等) ...