Here are some issues in your code:
- Infinite loop: In case of no path from source to target - but there is a cycle in the graph, your algorithm should return
0
- however, it is stuck in an infinite loop instead. - Counting wrong paths: Let's assume the
target
is at depth4
from thesource
, and is reached by the pathsource->v1->v2->target
. Now, assume you also have a pathsource->v3->v4->v5->target
in your graph, and for some reasonv4
was inserted to the queue beforetarget
(it can happen, there is no restriction on the orderings among these 2). You would also addtarget
again to the queue for the edge(v5,target)
, and also count the pathsource->v3->v4->v5->target
, but this is not a shortest path - but you did count it...
Have a look on this graph for example:
In the above, you first start from s
, and add all its neighbors to the queue. Now, let's assume v2
is added before v1
(that can happen, nothing prevents it..)
Now, at the next step, v2
will be expanded and you will add v3
to the queue.
Next, v1
is processed and target
is added to the queue.
Now, v3
is processed and add target
to the queue again.
Now, target
is processed, count
is increased, and the flag found
is set.
The queue is not empty yet, you now process target
- and increase count
again.
As a result, when done - count == 2
, but there is only 1 shortest path. This happens because you also counted the path s->v2->v3->t
.