I am currently trying to traverse all paths from source to destination in a graph which uses adjacency matrix. I have been trying to do it in BFS way.Thanks for the help. I
Apparently it is impossible to retrieve all paths from a given source to a given terminal via Breadth-First search. Consider the following class of graphs.
For any nonnegative integer n
, let
V := {v_1,...,v2_n} // inner vertices
union
{s, t}, // source and terminal
E := { {v_i,v+2,} : i < 2n-2 } // horizontal edges
union
{ {v_i,v_i+3} : i < 2n-3, i is odd } // cross edges from top to bottom
union
{ {v_i,v_i+3} : i < 2n-3, i is even } // cross edges from bottom to top
union
{ {s,v_1}, {s,v_2}, {t,v_2n-1}, {t,v_2n} } // source and terminal
Informally, the graph consists out of two rows of vertices with n
columns each, to the left there is a source node and to the right there is a terminal node. For each path from s
to t
, you can choose for each column to stay in the current row or to switch to the other row.
In total, there are 2^n
different paths from s
to t
, as for each column there are two possibilities to chose the row.
On the other hand, Breadth-First search yields a runtime bound which is polynomial in the encoding length of the graph; this means that Breadth-first search, in general, cannot generate all possible paths from a given source to a given terminal. Furthermore, if the graph contains a cycle, the number of paths might be inifinite via repetition of the cycle.