-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06-28-ReconstructItenary.java
More file actions
43 lines (39 loc) · 1.52 KB
/
06-28-ReconstructItenary.java
File metadata and controls
43 lines (39 loc) · 1.52 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
// origin -> list of destinations
HashMap<String, LinkedList<String>> flightMap = new HashMap<>();
LinkedList<String> result = null;
public List<String> findItinerary(List<List<String>> tickets) {
// Step 1). build the graph first
for (List<String> ticket : tickets) {
String origin = ticket.get(0);
String dest = ticket.get(1);
if (this.flightMap.containsKey(origin)) {
LinkedList<String> destList = this.flightMap.get(origin);
destList.add(dest);
} else {
LinkedList<String> destList = new LinkedList<String>();
destList.add(dest);
this.flightMap.put(origin, destList);
}
}
// Step 2). order the destinations
this.flightMap.forEach((key, value) -> Collections.sort(value));
this.result = new LinkedList<String>();
// Step 3). post-order DFS
this.DFS("JFK");
return this.result;
}
protected void DFS(String origin) {
// Visit all the outgoing edges first.
if (this.flightMap.containsKey(origin)) {
LinkedList<String> destList = this.flightMap.get(origin);
while (!destList.isEmpty()) {
// while we visit the edge, we trim it off from graph.
String dest = destList.pollFirst();
DFS(dest);
}
}
// add the airport to the head of the itinerary
this.result.offerFirst(origin);
}
}