triangle-exclamationDijkstra's Shortest Path

About

An algorithm to find shortest path, meaning find the edge connections with smallest weight.

circle-info

Don't use negative weight.

Drawing

Array Solution

circle-info

This algorithm will run on O(V2+E)O(V² + E) because of the way it uses to get the next lowest unseen node.

seen array has size V, and the while loop will run for each node on the graph in worst case, making it VVV*V.

circle-exclamation

The way this specific algorithm works is

  1. Will start from the source node (Ex.: Node 0), and check how much it costs to go to each of the unseen neighbors (Node 1 and Node 2).

    1. After this check it will save:

      1. In weights how much it costs to get to Node 1 = 1 and Node 2 = 5.

      2. In path it will have that the best way yet to get to Node 1 and Node 2 is from Node 0.

  2. Then it will check the next unseen node that has the lowest weight in weights. (So it will try to stay on the best path). In this example it will check now Node 1, and its unseen neighbors.

    1. After the check:

      1. In weights it will have that to get to Node 2 = 7 and Node 3 = 1. But we already know that there is a better path for Node 2 which is from Node 0, so reaching Node 2 from Node 1 is ignored.

      2. In path we have now that reaching Node 1 & 2 should be from Node 0 and reaching Node 3 should be from Node 1.

  3. Step 2 is repeated until there are no more unseen nodes. The algorithm will prioritize paths with lowest weight and will override them if a better one is found.

  4. At the end it just reconstruct the path to return it.

Heap Solution

Last updated