1
$\begingroup$

I have a graph in which I have to find the shortest path from A to H(There are A...H edges).
Weights:
A-B: 3
A-C: 5
B-C: 1
B-F: 1
C-F: 1
The problem arises when I reach (select) B. B-C is 1 and B-F is 1.
For the next step, if I select C, the path will eventually be longer than if I go B-F. How do I decide which point to select?

Edit:

In the image, we can see the obvious shortest path is a-b-f-e-h (total weight being 9). If we go via C, the path would be a-b-c-f-e-h (amounting to 10).

image of the graph

  • 0
    Beware of your geometric intuition, although it seems longer on the drawing, the path abfdgh is actually shorter than abfeh, with a weight of $8$ (I think the drawing is deliberately misleading to make a point).2017-01-18
  • 0
    @JoelCohen Yeah I got your point. If I follow the algorithm as explained by dimpol I would get the same answer.2017-01-18

1 Answers 1

3

It doesn't matter which one you select, the algorithm will always find a shortest path. The only difference is that it might find a different path of equal length if you make a different choice here.

So the step by step solution in this case is: Initially, the distance to A is 0 and all other distances are infinite.
Next A is the closest unvisited node, so we mark A visited and set the distances:
$B = \min\{3,\infty\}=3$
$C = \min\{5,\infty\}=5$
$D = \min\{6,\infty\}=6$
Next B is the closest unvisited node, so we mark B visited and set the distances:
$C = \min\{3+1,5\}=4$
$E = \min\{3+5,\infty\}=8$
$F = \min\{3+1,\infty\}=4$
At this point we could choose either C or F, so lets choose C. So we mark C as visited and set the distances:
$D = \min\{4+2,6\}=6$
$F = \min\{4+2,4\}=4$
Note that in the last step, we didn't change the path to F. The old path to F was shorter. Now we pick F, since this is the unique node that is the minimum distance univisited node. So we set F to visited and set:
$E = \min\{4+2,8\}=6$
$G = \min\{4+4,\infty\}=8$
$H = \min\{4+8,\infty\}=12$
After this, we visit D and E (in arbitrary order), then G and finally H will be the unvisited node with the minimum distance, so then we will finally visit H.

  • 0
    I have added an image of the graph. Please tell me what should be the correct answer here and how to solve it.2017-01-18
  • 0
    @Saksham Chawla : The point is that there might possibly be several correct answers (the algorithm will eventually give you one of them, depending on your choice).2017-01-18
  • 0
    I got your point. _The old path to F was shorter_. That was where I was confused. I didn't know if we could rollback to the previous step and use A-B-F instead of A-B-C-F. Got it, thanks!2017-01-18