-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.java
31 lines (30 loc) · 998 Bytes
/
Solution.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
30
31
class Solution {
void dfs(Map<String, Queue<String>> adjLists, List<String> ans, String curr) {
Queue<String> neighbors = adjLists.get(curr);
if (neighbors == null) {
ans.add(curr);
return;
}
while (!neighbors.isEmpty()) {
String neighbor = neighbors.poll();
dfs(adjLists, ans, neighbor);
}
ans.add(curr);
return;
}
public List<String> findItinerary(List<List<String>> tickets) {
Map<String, Queue<String>> adjLists = new HashMap<>();
for (List<String> ticket : tickets) {
String from = ticket.get(0);
String to = ticket.get(1);
if (!adjLists.containsKey(from)) {
adjLists.put(from, new PriorityQueue<>());
}
adjLists.get(from).add(to);
}
List<String> ans = new ArrayList<>();
dfs(adjLists, ans, "JFK");
Collections.reverse(ans);
return ans;
}
}