假设我们有一个由成对的出发和到达机场(例如[from,to])表示的机票列表,我们必须按顺序查找行程。所有的门票都属于一个从钦奈出发的人。因此,行程必须从钦奈开始。
因此,如果输入类似于[[“孟买”,“加尔各答”],[“钦奈”,“孟买”],[“德里”,“班加罗尔”],[“加尔各答”,“德里”]],则输出将是[“钦奈”,“孟买”,“加尔各答”,“德里”,“班加罗尔”]。
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector <string> ret; map < string, multiset <string> > graph; vector<string> findItinerary(vector<vector<string>>& tickets) { for(int i = 0; i < tickets.size(); i++){ string u = tickets[i][0]; string v = tickets[i][1]; graph[u].insert(v); } visit("Chennai"); reverse(ret.begin(), ret.end()); return ret; } void visit(string airport){ while(graph[airport].size()){ string x = *(graph[airport].begin()); graph[airport].erase(graph[airport].begin()); visit(x); } ret.push_back(airport); } }; main(){ Solution ob; vector<vector<string>> v = {{"Mumbai", "Kolkata"}, {"Chennai", "Mumbai"}, {"Delhi", "Bangalore"}, {"Kolkata", "Delhi"}}; print_vector(ob.findItinerary(v)); }
{{"Mumbai", "Kolkata"}, {"Chennai", "Mumbai"}, {"Delhi", "Bangalore"}, {"Kolkata", "Delhi"}}
输出结果
[Chennai, Mumbai, Kolkata, Delhi, Bangalore, ]