/
ReconstructItinerary.java
84 lines (69 loc) · 2.09 KB
/
ReconstructItinerary.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
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// https://leetcode.com/problems/reconstruct-itinerary
class Solution {
List<String> res;
public List<String> findItinerary(List<List<String>> tickets) {
Map<String, Integer> indexMap = buildIndexMap(tickets);
String[] nodePositions = invertIndexMap(indexMap);
int nodes = indexMap.size();
int edges = tickets.size();
int[][] adj = new int[nodes][nodes];
for (var ticket: tickets) {
String from = ticket.get(0);
String to = ticket.get(1);
adj[indexMap.get(from)][indexMap.get(to)] += 1;
}
build(indexMap, nodePositions, adj, "JFK", edges, new Stack<>());
return res;
}
boolean build(
Map<String, Integer> indexMap,
String[] nodePositions,
int[][] adj,
String curr,
int edges,
Stack<String> path
) {
path.push(curr);
if (edges == 0) {
if (res == null) {
res = new ArrayList<>(path);
}
return true;
}
int pos = indexMap.get(curr);
boolean r = false;
for (int i = 0; i < adj[pos].length; i++) {
if (adj[pos][i] > 0) {
adj[pos][i] -= 1;
r |= build(indexMap, nodePositions, adj, nodePositions[i], edges - 1, path);
adj[pos][i] += 1;
if (r) {
break;
}
}
}
path.pop();
return r;
}
Map<String, Integer> buildIndexMap(List<List<String>> tickets) {
Set<String> set = new TreeSet<>();
Map<String, Integer> map = new HashMap<>();
for (var e: tickets) {
for (var x: e) {
set.add(x);
}
}
int i = 0;
for (String x: set) {
map.put(x, i++);
}
return map;
}
String[] invertIndexMap(Map<String, Integer> map) {
String[] res = new String[map.size()];
for (var e: map.entrySet()) {
res[e.getValue()] = e.getKey();
}
return res;
}
}