Dijkstra's Algorithm: Why is it needed to find minimum-distance element in the queue

Take a look at this sample:

1-(6)-> 2 -(7)->3
  \          /
   (7)     (2)
     \    /
       4

I.e. you have edge with length 6 from 1 to 2, edge with length 7 from 2 to 3, edge with length 7 from 1 to 4 and edge from 4 to 3. I believe your algorithm will think shortest path from 1 to 3 has length 13 through 2, while actually best solution is with length 9 through 4.

Hope this make it clear.

EDIT: sorry this example did not brake the code. Have a look at this one:

8 9 1 3
1 5 6
5 3 2
1 2 7
2 3 2
1 4 7
4 3 1
1 7 3
7 8 2
8 3 2

Your output is Yes 8. While a path 1->7->8->3 takes only 7. Here is a link on ideone


I think your code has the wrong time complexity. Your code compares (almost) all pairs of nodes, which is of quadratic time complexity.

Try adding 10000 nodes with 10000 edges and see if the code can execute within 1 seconds.