Topic Connection
https://leetcode.com/problems/reconstruct-itinerary/
Reconstruct itinerarydescription
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 departs from JFK
. Thus, the itinerary must begin with JFK
.
Note:
- If There is multiple valid itineraries, you should return the itinerary that have the smallest lexical order when read as A single string. For example, the itinerary have
["JFK", "LGA"]
a smaller lexical order than ["JFK", "LGB"]
.
- All airports is represented by three capital letters (IATA code).
- Assume all tickets form at least one valid itinerary.
Example 1:
tickets
=[["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Return ["JFK", "MUC", "LHR", "SFO", "SJC"]
.
Example 2:
tickets
=[["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Return ["JFK","ATL","JFK","SFO","ATL","SFO"]
.
Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]
. But it's larger in lexical order.
The main topic: from "JFK" to find a sequence so that all the tickets run out, note that the result requires minimal dictionary order.
Idea: Deep search, note to mark the nodes that have been visited (Recall node restore when backtracking).
PS: Run out of $n$ tickets, of course, need to use a $n+1$ point
Class Solution {public:vector<string> Finditinerary (vector<pair<string, string>> tickets) {V ector<string> Res; if (Tickets.empty ()) return res; for (auto &r:tickets) Mp[r.first].insert ({R.second, false}); Res.push_back ("JFK"); DFS ("JFK", Res, tickets.size ()); return res; } bool Dfs (string from, vector<string> &res, int n) {if (int) res.size () = = n + 1) return true; for (Auto R = Mp[from].begin (); R! = Mp[from].end (); ++r) {String temp = (*r). First; Auto C = mp[from].find ({temp, false}); if (c = = Mp[from].end ()) continue; Res.push_back (temp); Mp[from].erase (c); Mp[from].insert ({temp, true}); if (Dfs (temp, res, n)) return true; Res.pop_back (); c = Mp[from].find ({temp, true}); if (c = = Mp[from].end ()) continue; Mp[from].erase (c); Mp[from].insert ({Temp, false}); } return false; }private:unordered_map<string, multiset<pair<string, bool>>> MP;};
Leetcode 332 Reconstruct itinerary