Example 1
- Input
- tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
- Output
- ["JFK","ATL","JFK","SFO","ATL","SFO"]
The route ["JFK","SFO","ATL","JFK","ATL","SFO"] also uses every ticket but is larger in lexical order.
Given every flight ticket as a directed edge, rebuild the complete trip that starts at 'JFK' and uses each ticket exactly once, choosing the smallest lexical order when several trips work.
You are given a list of airline tickets where each tickets[i] = [from, to] is one directed flight from airport from to airport to. Reconstruct the full itinerary that starts at airport JFK and uses every ticket exactly once, returning the airports in visiting order.
When several itineraries consume all tickets, return the one that is smallest in lexical order when read as a single string. The input always admits at least one valid itinerary, and duplicate tickets between the same airports may appear.
1 <= tickets.length <= 300tickets[i].length == 2The route ["JFK","SFO","ATL","JFK","ATL","SFO"] also uses every ticket but is larger in lexical order.
Only one ordering consumes every ticket: JFK to MUC to LHR to SFO to SJC.
KUL is smaller than NRT but has no departure, so taking it first strands two tickets. The NRT cycle must come before the final JFK to KUL flight.
One ticket needs two airport entries: the starting JFK and its only destination ATL.
The two identical JFK to ATL tickets are separate flights. Returning to JFK between them consumes both copies exactly once.
Tickets are directed edges, and repeated airport names are allowed because the restriction is on tickets, not airports. Example 1 must use both departures from JFK and both from ATL. A small next airport is desirable only if the remaining tickets can still be used: with JFK to KUL, JFK to NRT and NRT to JFK, choosing KUL immediately gets stuck. Backtracking tests whether a choice can finish; postorder traversal instead delays each stuck airport until the end of the final itinerary.
Reveal DFS Backtracking Search: intuition, complexity, and code
pop takes it in time; exploration order alone is not the final route.ATL to JFK back to ATL resolve naturally since the unwind order places the cycle interior before its entry airport.tickets.length + 1.When a graph problem demands using every edge exactly once, think Eulerian trail and build the answer with postorder appends: consume edges on the way down and record vertices on the way back up.