|
| 1 | +/** |
| 2 | + * 332. Reconstruct Itinerary |
| 3 | + * https://leetcode.com/problems/reconstruct-itinerary/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure |
| 7 | + * and the arrival airports of one flight. Reconstruct the itinerary in order and return it. |
| 8 | + * |
| 9 | + * All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with |
| 10 | + * "JFK". If there are multiple valid itineraries, you should return the itinerary that has the |
| 11 | + * smallest lexical order when read as a single string. |
| 12 | + * |
| 13 | + * For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. |
| 14 | + * |
| 15 | + * You may assume all tickets form at least one valid itinerary. You must use all the tickets once |
| 16 | + * and only once. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {string[][]} tickets |
| 21 | + * @return {string[]} |
| 22 | + */ |
| 23 | +var findItinerary = function(tickets) { |
| 24 | + const graph = new Map(); |
| 25 | + const itinerary = []; |
| 26 | + |
| 27 | + for (const [from, to] of tickets) { |
| 28 | + if (!graph.has(from)) { |
| 29 | + graph.set(from, []); |
| 30 | + } |
| 31 | + graph.get(from).push(to); |
| 32 | + } |
| 33 | + |
| 34 | + for (const [_, destinations] of graph) { |
| 35 | + destinations.sort().reverse(); |
| 36 | + } |
| 37 | + |
| 38 | + dfs('JFK'); |
| 39 | + |
| 40 | + return itinerary.reverse(); |
| 41 | + |
| 42 | + function dfs(airport) { |
| 43 | + while (graph.has(airport) && graph.get(airport).length) { |
| 44 | + dfs(graph.get(airport).pop()); |
| 45 | + } |
| 46 | + itinerary.push(airport); |
| 47 | + } |
| 48 | +}; |
0 commit comments