-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreconstruct-itinerary.java
More file actions
70 lines (58 loc) · 1.93 KB
/
reconstruct-itinerary.java
File metadata and controls
70 lines (58 loc) · 1.93 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// 332. Reconstruct Itinerary (10/6/55336)
// Runtime: 8 ms (20.19%) Memory: 43.42 MB (93.53%)
class Solution {
// origin -> list of destinations
HashMap<String, List<String>> flightMap = new HashMap<>();
HashMap<String, boolean[]> visitBitmap = new HashMap<>();
int flights = 0;
List<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)) {
List<String> destList = this.flightMap.get(origin);
destList.add(dest);
} else {
List<String> destList = new LinkedList<String>();
destList.add(dest);
this.flightMap.put(origin, destList);
}
}
// Step 2). order the destinations and init the visit bitmap
for (Map.Entry<String, List<String>> entry : this.flightMap.entrySet()) {
Collections.sort(entry.getValue());
this.visitBitmap.put(entry.getKey(), new boolean[entry.getValue().size()]);
}
this.flights = tickets.size();
LinkedList<String> route = new LinkedList<String>();
route.add("JFK");
// Step 3). backtracking
this.backtracking("JFK", route);
return this.result;
}
protected boolean backtracking(String origin, LinkedList<String> route) {
if (route.size() == this.flights + 1) {
this.result = (List<String>) route.clone();
return true;
}
if (!this.flightMap.containsKey(origin))
return false;
int i = 0;
boolean[] bitmap = this.visitBitmap.get(origin);
for (String dest : this.flightMap.get(origin)) {
if (!bitmap[i]) {
bitmap[i] = true;
route.add(dest);
boolean ret = this.backtracking(dest, route);
route.pollLast();
bitmap[i] = false;
if (ret)
return true;
}
++i;
}
return false;
}
}