Skip to content

Commit

Permalink
⚡️ use PriorityQueue in distanceFrom
Browse files Browse the repository at this point in the history
  • Loading branch information
twentylemon committed Dec 20, 2024
1 parent 5bc06fd commit 94d720d
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/main/scala/org/lemon/advent/lib/graph/fill.scala
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,16 @@ def fill[N](adjacency: N => Seq[N], start: N): Set[N] =
*/
def distanceFrom[N, D: Numeric](adjacency: N => Seq[(N, D)], end: N): Map[N, D] =
val distances = mutable.Map(end -> summon[Numeric[D]].zero)
val queue = mutable.Queue(end)
given Ordering[(N, D)] = Ordering.by[(N, D), D](_._2)
val queue = mutable.PriorityQueue(distances.head)

while !queue.isEmpty do
val node = queue.dequeue
val node = queue.dequeue._1
val dist = distances(node)
queue ++= adjacency(node)
.filter((neigh, d) => distances.get(neigh).forall(_ > dist + d))
.tapEach((neigh, d) => distances(neigh) = dist + d)
.map(_._1)

distances.toMap

/** Performs a breadth first fill of the graph from the starting node, returning
Expand Down

0 comments on commit 94d720d

Please sign in to comment.