给你一份航线列表 tickets ,其中 tickets[i] = [fromi, toi] 表示飞机出发和降落的机场地点。请你对该行程进行重新规划排序。
所有这些机票都属于一个从 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 <= 300
tickets[i].length == 2
fromi.length == 3
toi.length == 3
fromi 和 toi 由大写英文字母组成
fromi != toi
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reconstruct-itinerary
解法:
欧拉路径问题,本题与一般的欧拉路径问题就多了一个以字典序最小为条件。那么只需要在深度优先搜索的时候,先走字典序小的字符串。
class Solution {
struct cmp{
bool operator()(const string &a, const string &b)
{
return a>b;
}
};
vector<string> ans;
void dfs(string u, unordered_map<string, priority_queue<string, vector<string>, greater<string>>> &ma)
{
while (!ma[u].empty())
{
string v = ma[u].top();
ma[u].pop();
dfs(v, ma);
}
ans.push_back(u);
return;
}
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
unordered_map<string, priority_queue<string, vector<string>, greater<string>>> ma;
unordered_map<string, int> ind, outd;
for (auto &ticket : tickets)
{
string u = ticket[0], v = ticket[1];
ma[u].push(v);
++ind[v], ++outd[u];
}
//string start = tickets[0][0];
//for (auto &out : outd)
//{
//if (out.second == ind[out.first] + 1)
//{
//start = out.first;
//break;
//}
//}
dfs("JFK", ma);
reverse(ans.begin(), ans.end());
return ans;
}
};