|
| 1 | +package graph; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * Description: https://leetcode.com/problems/reconstruct-itinerary |
| 7 | + * Difficulty: Hard |
| 8 | + * Time complexity: O(V ^ E) |
| 9 | + * Space complexity: O(V + E) |
| 10 | + */ |
| 11 | +public class ReconstructItinerary { |
| 12 | + |
| 13 | + private static final String START = "JFK"; |
| 14 | + |
| 15 | + public List<String> findItinerary(List<List<String>> tickets) { |
| 16 | + Map<String, List<Ticket>> adjList = buildAdjList(tickets); |
| 17 | + |
| 18 | + List<String> itinerary = new ArrayList<>(); |
| 19 | + itinerary.add(START); |
| 20 | + int[] usedTickets = new int[tickets.size()]; |
| 21 | + |
| 22 | + return findItinerary(START, adjList, usedTickets, itinerary); |
| 23 | + } |
| 24 | + |
| 25 | + private List<String> findItinerary( |
| 26 | + String current, |
| 27 | + Map<String, List<Ticket>> adjList, |
| 28 | + int[] usedTickets, |
| 29 | + List<String> currentItinerary) { |
| 30 | + if (currentItinerary.size() == usedTickets.length + 1) { |
| 31 | + return currentItinerary; |
| 32 | + } |
| 33 | + |
| 34 | + for (Ticket next : adjList.getOrDefault(current, List.of())) { |
| 35 | + if (usedTickets[next.index] == 0) { |
| 36 | + usedTickets[next.index] = 1; |
| 37 | + currentItinerary.add(next.destination); |
| 38 | + |
| 39 | + List<String> itinerary = findItinerary(next.destination, adjList, usedTickets, currentItinerary); |
| 40 | + if (!itinerary.isEmpty()) return itinerary; |
| 41 | + |
| 42 | + usedTickets[next.index] = 0; |
| 43 | + currentItinerary.remove(currentItinerary.size() - 1); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return List.of(); |
| 48 | + } |
| 49 | + |
| 50 | + private Map<String, List<Ticket>> buildAdjList(List<List<String>> tickets) { |
| 51 | + Map<String, List<Ticket>> adjList = new HashMap<>(); |
| 52 | + for (int i = 0; i < tickets.size(); i++) { |
| 53 | + List<String> ticket = tickets.get(i); |
| 54 | + adjList.computeIfAbsent(ticket.get(0), __ -> new ArrayList<>()).add(new Ticket(ticket.get(1), i)); |
| 55 | + } |
| 56 | + |
| 57 | + for (List<Ticket> t : adjList.values()) { |
| 58 | + t.sort(Comparator.comparing(a -> a.destination)); |
| 59 | + } |
| 60 | + |
| 61 | + return adjList; |
| 62 | + } |
| 63 | + |
| 64 | + private record Ticket(String destination, int index) { |
| 65 | + } |
| 66 | +} |
0 commit comments