Skip to content

Commit 25ba032

Browse files
committed
TSP: make 'visited' an immutable list
Performance impact on "All in a single night" (day 9 of 2015, both parts together, approximated measuremnts): - from 949us to 797us
1 parent a266c54 commit 25ba032

File tree

1 file changed

+6
-14
lines changed

1 file changed

+6
-14
lines changed

src/main/kotlin/de/ronny_h/aoc/extensions/graphs/TravelingSalesman.kt

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ data class TravelingSalesmanProblemSolution(val length: Int, val path: List<Int>
77

88
// should be larger than any other single weight in the graph
99
const val MAX_WEIGHT = 10_000_000
10-
private const val UNSET = -1
1110

1211
/**
1312
* A TSP implementation inspired from https://www.geeksforgeeks.org/dsa/traveling-salesman-problem-using-branch-and-bound-2/
@@ -21,7 +20,7 @@ class TravelingSalesman(private val adj: List<List<Int>>) {
2120
private var finalPath = listOf<Int>()
2221

2322
// visited keeps track of the already visited nodes in a particular path
24-
private val visited = mutableListOf<Int>()
23+
private var visited = listOf<Int>()
2524

2625
// Stores the final minimum weight of shortest tour.
2726
private var finalLength: Int = Int.MAX_VALUE
@@ -99,7 +98,7 @@ class TravelingSalesman(private val adj: List<List<Int>>) {
9998
// currentBound + currentWeight is the actual lower bound for the node that we have arrived on
10099
// If current lower bound < finalLength, we need to explore the node further
101100
if (currentBound + currentWeight < finalLength) {
102-
visited.add(i)
101+
visited += i
103102
tspRecursive(currentBound, currentWeight, level + 1, currentPath + i)
104103
}
105104

@@ -108,13 +107,8 @@ class TravelingSalesman(private val adj: List<List<Int>>) {
108107
currentWeight -= adj[currentPath[level - 1]][i]
109108
currentBound = temp
110109

111-
// Also reset the visited array
112-
visited.clear()
113-
for (j in 0..<level) {
114-
if (currentPath[j] != UNSET) {
115-
visited.add(currentPath[j])
116-
}
117-
}
110+
// Also reset the visited list
111+
visited = currentPath
118112
}
119113
}
120114
}
@@ -130,10 +124,8 @@ class TravelingSalesman(private val adj: List<List<Int>>) {
130124
val currentBound = ((0..<N).sumOf { firstMin(it) + secondMin(it) } / 2.0).toInt()
131125

132126
// We start at vertex 1 so the first vertex in currentPath is 0
133-
visited.add(0)
134-
val currentPath = listOf(0)
135-
136-
tspRecursive(currentBound, 0, 1, currentPath)
127+
visited = listOf(0)
128+
tspRecursive(currentBound, 0, 1, listOf(0))
137129
}
138130
}
139131

0 commit comments

Comments
 (0)