[LeetCode] Reconstruct Itinerary

332. Reconstruct Itinerary

You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.

All of the tickets belong to a man who departs from “JFK”, thus, the itinerary must begin with “JFK”. 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”].

You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
map<string, map<string, int>> m;
int arrive;

bool build(vector<string> &res, const string &from) {
if (res.size() == arrive) return true;
for (auto &to : m[from]) {
if (!to.second) continue;
res.push_back(to.first);
to.second--;
if (build(res, to.first)) return true;
to.second++;
res.pop_back();
}
return false;
}

public:
vector<string> findItinerary(vector<vector<string>> &tickets) {
arrive = tickets.size() + 1;
for (auto &t : tickets) {
m[t.front()][t.back()]++;
}
vector<string> res{"JFK"};
build(res, "JFK");
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/11/PS/LeetCode/reconstruct-itinerary/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.