Skip to content

Commit e57d4de

Browse files
committed
Add 332_Reconstruct_Itinerary.java
1 parent ae97a54 commit e57d4de

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Graphs/332_Reconstruct_Itinerary.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public List<String> findItinerary(List<List<String>> tickets) {
3+
if (tickets == null || tickets.size() == 0) {
4+
return Collections.emptyList();
5+
}
6+
7+
LinkedList<String> result = new LinkedList<>();
8+
Map<String, PriorityQueue<String>> graph = new HashMap<>();
9+
10+
for (List<String> t : tickets) {
11+
graph.putIfAbsent(t.get(0), new PriorityQueue<>());
12+
graph.get(t.get(0)).add(t.get(1));
13+
}
14+
15+
dfs("JFK", graph, result);
16+
17+
return result;
18+
}
19+
20+
private void dfs(String departure, Map<String, PriorityQueue<String>> graph, LinkedList<String> path) {
21+
PriorityQueue<String> arrivals = graph.get(departure);
22+
23+
while (arrivals != null && !arrivals.isEmpty()) {
24+
dfs(arrivals.poll(), graph, path);
25+
}
26+
27+
path.addFirst(departure);
28+
}
29+
}

0 commit comments

Comments
 (0)