diff --git a/solution/0300-0399/0332.Reconstruct Itinerary/README.md b/solution/0300-0399/0332.Reconstruct Itinerary/README.md index caca416c94500..10906a75fd998 100644 --- a/solution/0300-0399/0332.Reconstruct Itinerary/README.md +++ b/solution/0300-0399/0332.Reconstruct Itinerary/README.md @@ -98,6 +98,44 @@ class Solution { } ``` +### **C++** + +```cpp +class Solution { +public: + vector findItinerary(vector>& tickets) { + unordered_map, greater>> g; + vector ret; + + // Initialize the graph + for (const auto& t : tickets) { + g[t[0]].push(t[1]); + } + + findItineraryInner(g, ret, "JFK"); + + ret = {ret.rbegin(), ret.rend()}; + + return ret; + } + + void findItineraryInner(unordered_map, greater>>& g, vector& ret, string cur) { + if (g.count(cur) == 0) { + // This is the end point + ret.push_back(cur); + return; + } else { + while (!g[cur].empty()) { + auto front = g[cur].top(); + g[cur].pop(); + findItineraryInner(g, ret, front); + } + ret.push_back(cur); + } + } +}; +``` + ### **...** ``` diff --git a/solution/0300-0399/0332.Reconstruct Itinerary/README_EN.md b/solution/0300-0399/0332.Reconstruct Itinerary/README_EN.md index 711fa5d3d6131..99c61037d1859 100644 --- a/solution/0300-0399/0332.Reconstruct Itinerary/README_EN.md +++ b/solution/0300-0399/0332.Reconstruct Itinerary/README_EN.md @@ -88,6 +88,44 @@ class Solution { } ``` +### **C++** + +```cpp +class Solution { +public: + vector findItinerary(vector>& tickets) { + unordered_map, greater>> g; + vector ret; + + // Initialize the graph + for (const auto& t : tickets) { + g[t[0]].push(t[1]); + } + + findItineraryInner(g, ret, "JFK"); + + ret = {ret.rbegin(), ret.rend()}; + + return ret; + } + + void findItineraryInner(unordered_map, greater>>& g, vector& ret, string cur) { + if (g.count(cur) == 0) { + // This is the end point + ret.push_back(cur); + return; + } else { + while (!g[cur].empty()) { + auto front = g[cur].top(); + g[cur].pop(); + findItineraryInner(g, ret, front); + } + ret.push_back(cur); + } + } +}; +``` + ### **...** ``` diff --git a/solution/0300-0399/0332.Reconstruct Itinerary/Solution.cpp b/solution/0300-0399/0332.Reconstruct Itinerary/Solution.cpp new file mode 100644 index 0000000000000..c9a7344be9fee --- /dev/null +++ b/solution/0300-0399/0332.Reconstruct Itinerary/Solution.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + vector findItinerary(vector>& tickets) { + unordered_map, greater>> g; + vector ret; + + // Initialize the graph + for (const auto& t : tickets) { + g[t[0]].push(t[1]); + } + + findItineraryInner(g, ret, "JFK"); + + ret = {ret.rbegin(), ret.rend()}; + + return ret; + } + + void findItineraryInner(unordered_map, greater>>& g, vector& ret, string cur) { + if (g.count(cur) == 0) { + // This is the end point + ret.push_back(cur); + return; + } else { + while (!g[cur].empty()) { + auto front = g[cur].top(); + g[cur].pop(); + findItineraryInner(g, ret, front); + } + ret.push_back(cur); + } + } +}; \ No newline at end of file