0332.重新安排行程
https://leetcode-cn.com/problems/reconstruct-itinerary
原题
给你一份航线列表 tickets ,其中 tickets[i] = [from[i], to[i]] 表示飞机出发和降落的机场地点。请你对该行程进行重新规划排序。
所有这些机票都属于一个从 JFK (肯尼迪国际机场)出发的先生,所以该行程必须从 JFK 开始。如果存在多种有效的行程,请你按字典排序返回最小的行程组合。
- 例如,行程
["JFK", "LGA"]与["JFK", "LGB"]相比就更小,排序更靠前。
假定所有机票至少存在一种合理的行程。且所有的机票 必须都用一次 且 只能用一次。
示例 1:
输入:tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]输出:["JFK","MUC","LHR","SFO","SJC"]
示例 2:
输入:tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
输出:["JFK","ATL","JFK","SFO","ATL","SFO"]
解释:另一种有效的行程是 ["JFK","SFO","ATL","JFK","ATL","SFO"] ,但是它字典排序更大更靠后。
提示:
1 <= tickets.length <= 300tickets[i].length == 2from[i].length == 3to[i].length == 3from[i]和to[i]由大写英文字母组成from[i] != to[i]
标签深度优先搜索 图 欧拉回路
思路
有向图的欧拉回路或者欧拉通路
代码
方法一:DFS
注意记录需要达到的机场的次数,以及 DFS 结束条件,当走过的顶点数为边数加1时结束递归,并且找到了最佳解决方案
class Solution {
private:
vector<string> result; // 记录遍历的结果
unordered_map<string, map<string, int>> u; // 某机场能到达的机场,并且记录应该到达几次
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
for(auto it: tickets){
u[it[0]][it[1]]++;
}
result.push_back("JFK");
int n = tickets.size(); // 航班数量
dfs(n);
return result;
}
bool dfs(int n){
if(result.size() == n+1) { // 到达的机场数 等于 航班数+1,结束
return true;
}
for(auto &it: u[result[result.size()-1]]){
if(it.second > 0){
it.second--;
result.push_back(it.first);
if(dfs(n)) return true;
it.second++;
result.pop_back();
}
}
return false;
}
};
方法二:Hierholzer 算法
遍历时,先将该边移除,然后递归,再将这条边加入到栈中
因为死胡同必然是最后到达的,那么会最先放到栈里,因此输出栈中的结果就好
class Solution {
private:
unordered_map<string, vector<string>> u;
vector<string> res;
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
for(auto it: tickets){
u[it[0]].push_back(it[1]);
}
for(auto &it: u){
sort(it.second.begin(), it.second.end());
}
int n = tickets.size();
dfs("JFK", n);
reverse(res.begin(), res.end());
return res;
}
void dfs(string a, int n){
while(u[a].size() > 0){
string k = u[a][0];
u[a].erase(u[a].begin());
dfs(k, n);
res.push_back(a);
}
if(res.empty()){ // 这是为了将最后遍历的那个节点加进去
res.push_back(a);
}
}
};
另一种写法,把加入到结果放在外面
class Solution {
private:
unordered_map<string, vector<string>> u;
vector<string> res;
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
for(auto it: tickets){
u[it[0]].push_back(it[1]);
}
for(auto &it: u){
sort(it.second.begin(), it.second.end());
}
dfs("JFK");
reverse(res.begin(), res.end());
return res;
}
void dfs(string a){
while(u[a].size() > 0){
string k = u[a][0];
u[a].erase(u[a].begin());
dfs(k);
}
res.push_back(a);
}
};
易错例子
[["JFK", "AAA"], ["JFK", "BBB"], ["BBB", "JFK"]]
[
](https://www.cnblogs.com/wkfvawl/p/9626163.html)
如果直接到 AAA,那么无法返回起点
