|
| 1 | +// https://leetcode.com/problems/reconstruct-itinerary |
| 2 | +// E = |flights|, V = |airports| N = E / V |
| 3 | +// T: O(V * NlogN) = O(E log(E / V)) |
| 4 | +// S: O(V + E) |
| 5 | + |
| 6 | +import java.util.ArrayList; |
| 7 | +import java.util.HashMap; |
| 8 | +import java.util.List; |
| 9 | +import java.util.Map; |
| 10 | +import java.util.PriorityQueue; |
| 11 | +import java.util.Queue; |
| 12 | + |
| 13 | +public class ReconstructItinerary { |
| 14 | + public List<String> findItinerary(List<List<String>> tickets) { |
| 15 | + final Map<String, Queue<String>> graph = createGraph(tickets); |
| 16 | + final List<String> result = new ArrayList<>(); |
| 17 | + dfs(graph, "JFK", result); |
| 18 | + return result.reversed(); |
| 19 | + } |
| 20 | + |
| 21 | + private static void dfs(Map<String, Queue<String>> graph, String current, List<String> result) { |
| 22 | + final Queue<String> queue = graph.getOrDefault(current, new PriorityQueue<>()); |
| 23 | + while (!queue.isEmpty()) { |
| 24 | + final String to = queue.poll(); |
| 25 | + dfs(graph, to, result); |
| 26 | + } |
| 27 | + result.add(current); |
| 28 | + } |
| 29 | + |
| 30 | + private static Map<String, Queue<String>> createGraph(List<List<String>> tickets) { |
| 31 | + final Map<String, Queue<String>> graph = new HashMap<>(); |
| 32 | + for (List<String> ticket : tickets) { |
| 33 | + final String from = ticket.get(0), to = ticket.get(1); |
| 34 | + final Queue<String> queue = graph.getOrDefault(from, new PriorityQueue<>()); |
| 35 | + queue.add(to); |
| 36 | + graph.putIfAbsent(from, queue); |
| 37 | + } |
| 38 | + return graph; |
| 39 | + } |
| 40 | +} |
0 commit comments