Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix implementation of Dijkstra's algorithm #1745

Merged
merged 3 commits into from
Mar 29, 2021
Merged

Fix implementation of Dijkstra's algorithm #1745

merged 3 commits into from
Mar 29, 2021

Conversation

thomash-acinq
Copy link
Member

Ensure that we only visit each node once in Dijkstra's algorithm.

Relying on `bestWeights` doesn't work if the node was added several times with exactly the same weight.
Copy link
Member

@t-bast t-bast left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch!

@@ -208,8 +209,9 @@ object Graph {
while (toExplore.nonEmpty && !targetFound) {
// node with the smallest distance from the target
val current = toExplore.dequeue() // O(log(n))
if (current.key != sourceNode) {
val currentWeight = bestWeights(current.key) // NB: there is always an entry for the current in the 'bestWeights' map
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you sure about that change?
At first glance getting the best weight from this map seems useful, doesn't it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's exactly the same weight. We already have it in current.weight, there is no point in getting it from somewhere else.

Actually we could remove bestWeights completely, it's not needed by the algorithm, the comparison between the different weights for a node is done inside the priority queue.
Now it's just used to know when to update bestEdges and it sometimes prevents adding useless weights to the priority queue.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the comparison between the different weights for a node is done inside the priority queue.

Right, I glossed over that point, once you realize this it's obviously not needed.

@t-bast t-bast merged commit e5429eb into master Mar 29, 2021
@pm47 pm47 deleted the shortest-path branch March 29, 2021 16:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants