Skip to content

Instantly share code, notes, and snippets.

@SuryaPratapK
Created June 29, 2020 03:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save SuryaPratapK/e2a72fa59167faefb2d2639519d33f8e to your computer and use it in GitHub Desktop.
Save SuryaPratapK/e2a72fa59167faefb2d2639519d33f8e to your computer and use it in GitHub Desktop.
class Solution {
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
unordered_map<string,multiset<string>> adj;
vector<string> ans;
int n=tickets.size();
//Make graph
for(int i=0;i<n;++i)
adj[tickets[i][0]].insert(tickets[i][1]);
stack<string> mystack;
mystack.push("JFK"); //JFK is our fixed starting point
while(!mystack.empty())
{
string src = mystack.top();
if(adj[src].size()==0) //No further travel possible
{
ans.push_back(src);
mystack.pop();
}
else
{
auto dst = adj[src].begin();
mystack.push(*dst);
adj[src].erase(dst);
}
}
reverse(ans.begin(),ans.end());
return ans;
}
};
static int fastio = []() {
#define endl '\n'
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(0);
return 0;
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment