forked from seanprashad/leetcode-patterns
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path332_Reconstruct_Itinerary.java
29 lines (22 loc) · 878 Bytes
/
332_Reconstruct_Itinerary.java
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
classSolution {
publicList<String> findItinerary(List<List<String>> tickets) {
if (tickets == null || tickets.size() == 0) {
returnCollections.emptyList();
}
LinkedList<String> result = newLinkedList<>();
Map<String, PriorityQueue<String>> graph = newHashMap<>();
for (List<String> t : tickets) {
graph.putIfAbsent(t.get(0), newPriorityQueue<>());
graph.get(t.get(0)).add(t.get(1));
}
dfs("JFK", graph, result);
returnresult;
}
privatevoiddfs(Stringdeparture, Map<String, PriorityQueue<String>> graph, LinkedList<String> path) {
PriorityQueue<String> arrivals = graph.get(departure);
while (arrivals != null && !arrivals.isEmpty()) {
dfs(arrivals.poll(), graph, path);
}
path.addFirst(departure);
}
}