1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Solution { private final List<String> ans = new LinkedList<>(); private final Map<String, PriorityQueue<String>> map = new HashMap<>();
public List<String> findItinerary(List<List<String>> tickets) { initMap(tickets); dfs("JFK"); Collections.reverse(ans); return ans; }
private void initMap(List<List<String>> tickets) { for (var pair : tickets) { String source = pair.get(0), destination = pair.get(1); if (!map.containsKey(source)) { PriorityQueue<String> destinations = new PriorityQueue<>(); destinations.add(destination); map.put(source, destinations); } else { map.get(source).add(destination); } } }
private void dfs(String pos) { while (map.containsKey(pos) && map.get(pos).size() != 0) { String tmp = map.get(pos).poll(); dfs(tmp); } ans.add(pos); } }
|