4

Consider the following weighted directed graph:

enter image description here

Let's consider node 1 as a starting node, according to the Dijkstra algorithm we have the following steps:

  1. node 1 marked visited.

  2. the shortest path to node 2 has weight 1. Mark node 2 visited.

  3. the shortest path to node 3 has weight 30. Mark node 3 visited. After that, according to algorithm node 3 has minimal path weight as 30, and cannot be changed. But, evidently, the shortest path to node3 is 4.

Can you, please point out any flaw in my interpretation of the algorithm?

JamieNguyen
  • 291
  • 3
  • 15
voipp
  • 1,243
  • 3
  • 18
  • 31
  • It starts to get wrong already in step 2. Please take another look at the description of the algorithm. – Henry Nov 01 '18 at 09:38

2 Answers2

3

The short answer is no, your understanding is incorrect.

Here is the correct algorithm:

Dijkstra's algorithm picks the unvisited vertex with the lowest distance, calculates the distance through it to each unvisited neighbor, and updates the neighbor's distance if smaller. Mark visited (set to red) when done with neighbors.

Source: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm

Your flaw is that we pick an unvisited vertex with lowest cost.

Andriy Berestovskyy
  • 8,059
  • 3
  • 17
  • 33
2

The following table states all the steps of the algorithm. The first column shows the node that is visited, the second column shows the nodes that have already been explored (but have not been visited yet) plus the neighbors of the currently visited node. All nodes are represented as triplets (n, d, p), where n is the node name, d is the distance from the start node, and p is the predecessor node. As other answers and comments have already mentioned, you will always visit the explored node with the minimum distance:

visited node | explored nodes
-------------+-------------------------
(1, 0, -)    | (2, 1, 1) (3, 30, 1)
(2, 1, 1)    | (3, 30, 1) (4, 2, 2)
(4, 2, 2)    | (3, 30, 1) (5, 3, 4)
(5, 3, 4)    | (3, 4, 5)     //distance of node 3 is updated
(3, 4, 5)    | 

Hence, the path to node 3 actually goes over all the other nodes as expected.

Nico Schertler
  • 32,049
  • 4
  • 39
  • 70