332 Reconstruct Itinerary
332. Reconstruct Itinerary
1. Question
2. Implementation
class Solution {
public List<String> findItinerary(String[][] tickets) {
List<String> route = new ArrayList<>();
if (tickets == null || tickets.length == 0) {
return route;
}
Map<String, PriorityQueue<String>> map = new HashMap<>();
for (String[] ticket : tickets) {
map.putIfAbsent(ticket[0], new PriorityQueue<>());
map.get(ticket[0]).add(ticket[1]);
}
dfs("JFK", map, route);
return route;
}
public void dfs(String airport, Map<String, PriorityQueue<String>> map, List<String> route) {
while (map.containsKey(airport) && !map.get(airport).isEmpty()) {
String nextAirport = map.get(airport).remove();
dfs(nextAirport, map, route);
}
route.add(0, airport);
}
}3. Time & Space Complexity
Last updated