這題使用許多資結技巧,
-hashtable用於紀錄tickets的起終點
-dfs用於深挖到從最起點至最終點
-heap(priority queue)用於把現在需要的一個一個推出
ref:https://leetcode.com/problems/reconstruct-itinerary/solutions/3973238/c-fast-code-18ms/?envType=daily-question&envId=2023-09-14
class Solution {
public:
#define pq priority_queue<string , vector<string>, greater<string>>
map<string, pq> mp;
vector<string> ans;
void dfs(string start){
if(mp[start].size() == 0){
ans.push_back(start);
return ;
}
auto &s = mp[start];
while(!s.empty()){
auto tmp = s.top();
s.pop();
dfs(tmp);
}
ans.push_back(start);
}
vector<string> findItinerary(vector<vector<string>>& tickets) {
mp.clear();
ans.clear();
for(auto i : tickets){
mp[i[0]].push(i[1]);
}
dfs("JFK");
reverse(begin(ans), end(ans));
return ans;
}
};