File tree Expand file tree Collapse file tree 1 file changed +9
-10
lines changed
src/main/kotlin/adventofcode/util/graph Expand file tree Collapse file tree 1 file changed +9
-10
lines changed Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments