Skip to content

Conversation

@Falke-Design
Copy link

Thank you for your sharing Dijkstra's Algorithm in JavaScript!

I have found a small optimization with a big impact, but I don't know if it is compatible with the "thinking" / "logic" behind Dijkstra's Algorithm.

If already a end distance is found, it don't goes anymore over the node which are farer away then the distance to the end node. This makes it much fast if there are many nodes in the graph.

Current code:
shortest-path-slow

With optimization :
shortest-path-fast

parents[child] = node;

// if already a end distance is found, we allow only ways which are shorter
if (!distances[endNode] || distances[endNode] > distance) {
Copy link
Author

Choose a reason for hiding this comment

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

This line is new

// save the distance to the object but if already a end distance is found, it must be shorter then it
// record the path
if ((!distances[child] || distances[child] > newdistance)
&& (!distances[endNode] || distances[endNode] > newdistance)) {
Copy link
Author

Choose a reason for hiding this comment

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

and this line is new

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.

1 participant