1. DFS Backtracking with Ticket Consumption
Intuition
Sort all tickets lexicographically. Run DFS with backtracking starting from JFK. At each step, try every unused ticket departing from the current airport in lexicographical order. The first path that successfully uses all tickets (path length == tickets.length + 1) is the lexicographically smallest Eulerian path.
Algorithm
- Sort tickets lexicographically.
- Track used tickets with a boolean array
usedof size E. - Define
dfs(curr, count, path): - If
count == tickets.length: - Save
pathand return true. - For each ticket i departing from
curr: - If
!used[i]: -
used[i] = true -
path.push(ticket.to) - If
dfs(ticket.to, count + 1, path)return true. -
path.pop(),used[i] = false(backtrack) - Return false.
- Run
dfs("JFK", 0, ["JFK"]).
#include <iostream>#include <vector>#include <string>#include <algorithm> bool dfsBacktrack(const std::string& curr, int usedCount, int totalTickets, std::vector<std::vector<std::string>>& tickets, std::vector<bool>& used, std::vector<std::string>& path) { if (usedCount == totalTickets) return true; for (size_t i = 0; i < tickets.size(); ++i) { if (!used[i] && tickets[i][0] == curr) { used[i] = true; path.push_back(tickets[i][1]); if (dfsBacktrack(tickets[i][1], usedCount + 1, totalTickets, tickets, used, path)) { return true; } path.pop_back(); used[i] = false; } } return false;} std::vector<std::string> findItineraryBacktrack(std::vector<std::vector<std::string>>& tickets) { std::sort(tickets.begin(), tickets.end()); std::vector<bool> used(tickets.size(), false); std::vector<std::string> path = {"JFK"}; dfsBacktrack("JFK", 0, tickets.size(), tickets, used, path); return path;} int main() { std::vector<std::vector<std::string>> tickets = { {"MUC","LHR"},{"JFK","MUC"},{"SFO","SJC"},{"LHR","SFO"} }; auto res = findItineraryBacktrack(tickets); std::cout << "Itinerary (Backtrack): "; for (const auto& s : res) std::cout << s << " "; std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(E!) in the worst-case when many dead ends require extensive backtracking. - Space complexity:
O(E) for the recursion stack and path array.