Skip to content

Commit 6868331

Browse files
committed
Fixing reachable implementation.
1 parent 32f7ff9 commit 6868331

File tree

1 file changed

+9
-10
lines changed
  • src/main/kotlin/adventofcode/util/graph

1 file changed

+9
-10
lines changed

src/main/kotlin/adventofcode/util/graph/Graphs.kt

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -63,16 +63,15 @@ object Graphs {
6363

6464
fun <V> reachable(start: V, maxSteps: Int = Int.MAX_VALUE, neighbors: (V) -> List<V>): Set<V> {
6565
val visited = mutableSetOf<V>()
66-
val queue = mutableListOf(Reachable(0, start))
67-
while (queue.isNotEmpty()) {
68-
val reachable = queue.removeFirst()
69-
visited += reachable.vertex
70-
if (reachable.steps < maxSteps) {
71-
neighbors(reachable.vertex)
72-
.filter { it !in visited }
73-
.map { Reachable(reachable.steps + 1, it) }
74-
.forEach { queue.addLast(it) }
75-
66+
val stack = mutableListOf(Pair(start, 0))
67+
while (stack.isNotEmpty()) {
68+
val (current, steps) = stack.removeFirst()
69+
if (steps > maxSteps) continue
70+
if (current !in visited) {
71+
visited.add(current)
72+
neighbors(current)
73+
.filter { it !in visited }
74+
.forEach { stack.add(Pair(it, steps + 1)) }
7675
}
7776
}
7877
return visited

0 commit comments

Comments
 (0)