I would like to find path of fixed length (given while running the program) in undirected graph. I\'m using adjacency matrix of my graph.
I tried to use some algorithms like
A single dfs ought to be sufficient:
void dfs(int start, int hops)
{
if(hops == k && start == t)
{
path++;
return;
}
else if(hops >= k)
return;
for(int w = 1; w <= n; w++)
if(routes[start][w])
dfs(w, hops + 1);
}
Here, k is the length of the path and routes[][] is the adjacency matrix of the graph. path is a global variable. This can account for cycles - it takes into account ALL paths of a given length. From main, call
path = 0;
dfs(source, k);
cout<
Note that the number of nodes is one more than the number of hops. Also note that if the length the path is huge, this function stacks up quickly. No pun intended.