forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path332-Reconstruct-Itinerary.java
More file actions
30 lines (26 loc) · 913 Bytes
/
332-Reconstruct-Itinerary.java
File metadata and controls
30 lines (26 loc) · 913 Bytes
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
class Solution {
public List<String> findItinerary(List<List<String>> tickets) {
LinkedList<String> itinerary = new LinkedList<>();
Map<String, PriorityQueue<String>> graph = new HashMap<>();
Stack<String> stack = new Stack<>();
for (List<String> ticket : tickets) {
graph
.computeIfAbsent(ticket.get(0), k -> new PriorityQueue<>())
.add(ticket.get(1));
}
stack.push("JFK");
while (!stack.isEmpty()) {
String nextDestination = stack.peek();
if (
!graph
.getOrDefault(nextDestination, new PriorityQueue<>())
.isEmpty()
) {
stack.push(graph.get(nextDestination).poll());
} else {
itinerary.addFirst(stack.pop());
}
}
return itinerary;
}
}