forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0332-reconstruct-itinerary.kt
45 lines (36 loc) · 1.25 KB
/
0332-reconstruct-itinerary.kt
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
package kotlin
class Solution {
fun findItinerary(tickets: List<List<String>>): List<String> {
val res = ArrayList<String>()
val map = HashMap<String, ArrayList<String>>()
for (t in tickets) {
if (map[t[0]] == null) {
map[t[0]] = ArrayList<String>()
}
map[t[0]]!!.add(t[1])
}
val sorted = map.mapValues {
ArrayList(it.value.sortedBy { it })
}
fun dfs(from: String) : Boolean {
res.add(from)
if (res.size == tickets.size + 1) return true
val dests = sorted[from] ?: return false
if (dests.isEmpty()) return false
val temp = ArrayList(dests)
for (t in temp) {
dests.remove(t)
if (dfs(t)) {
return true
} else {
// res.removeLast() // not available in leetcode
res.removeAt(res.lastIndex)
dests.add(t)
}
}
return false
}
dfs("JFK")
return res
}
}