Skip to content

Commit 2c0d49f

Browse files
authored
Merge pull request #857 from miladra/main
Add 332
2 parents c44c74f + 45395e0 commit 2c0d49f

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

java/332-Reconstruct-Itinerary.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public List<String> findItinerary(List<List<String>> tickets) {
3+
4+
LinkedList<String> itinerary = new LinkedList<>();
5+
Map<String, PriorityQueue<String>> graph = new HashMap<>();
6+
Stack<String> stack = new Stack<>();
7+
8+
for (List<String> ticket : tickets) {
9+
graph.computeIfAbsent(ticket.get(0), k -> new PriorityQueue<>()).add(ticket.get(1));
10+
}
11+
12+
13+
stack.push("JFK");
14+
while (!stack.isEmpty()) {
15+
String nextDestination = stack.peek();
16+
17+
if (!graph.getOrDefault(nextDestination, new PriorityQueue<>()).isEmpty()) {
18+
19+
stack.push(graph.get(nextDestination).poll());
20+
21+
} else {
22+
23+
itinerary.addFirst(stack.pop());
24+
25+
}
26+
}
27+
return itinerary;
28+
}
29+
}
30+

0 commit comments

Comments
 (0)