Shortest Path using BFS


Why is it printing all the incorrect distance of nodes from source?

@mohitsethia your code is printing correct distance of nodes from source.

Node 0 Distance from source is 0
Node 1 Distance from source is 1
Node 2 Distance from source is 2
Node 3 Distance from source is 3
Node 4 Distance from source is 4
Node 5 Distance from source is 5
This is the output I am getting, but I need the shortest distance from the source, doing which the output will be -->
Node 0 Distance from source is 0
Node 1 Distance from source is 1
Node 2 Distance from source is 2
Node 3 Distance from source is 1
Node 4 Distance from source is 2
Node 5 Distance from source is 3

there is no way you can reach the node 3 in single step since it is not connected with source 0 directly so how are you saying that shortest distance for 3 should be 1.
check what input you have taken make graph of the input you have taken and calculate distance in pen and paper then compare it with the output you are getting.

Okay, now I got the right answer. Actually I forgot to add edge between 3 and 0

1 Like