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 DFS or A*, but they only return the shortest path.
Nodes can't be visited again.
So let's say that my graph have 9 nodes and the shortest path is built from 4 nodes.
I want to have additional variable that will "tell" the algorithm that I want to find path which have 7 nodes (for example) and it will return nodes which are included in my expected path {1,2,4,5,6,7,8}.
Of course, if there is no solution for path that I want, it will return nothing (or it will return path close to my expactations, let's say 19 instead of 20).
Someone told be about DFS with backtracking, but I don't know anything about it.
Could someone explain how to use DFS with backtracking or recommend some other algorithms to solve that problem?
Backtracking indeed seems like a reasonable solution. The idea is to recursively find a path of the required length.
Psuedo code:
The above algorithm will generate all paths of required depth.
invokation with
DFS(depth,source,[])
(where[]
is an empty list).Note:
visited
set, and add each vertex when you append it to the found path, and remove it when you remove it from the path.A single dfs ought to be sufficient:
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
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.
Suppose you can find a path of length d in a graph then you can run this algorithm |V| times and find the longest path which is NP-complete. So you can try the following approach -
1) approximation algorithm 2) brute force approach (more suitable for programming). Use a GPU to accelerate your code.
Also it may be of interest to you that -
there exists a linear time algorithm for DAGs.
The problem as stated is NP-complete. Yo can trivially solve Hamiltonian Cycle Problem, given an efficient algorithm for solving Your problem.
Therefore, no polynomnial time solution exists (unless P=NP). For an exhaustive search, exponential time solution, check @amit's answer.
Try finding the longest path, then cutting it to the required length. The longest path is also called as diameter of the graph. The longest path can be found by running DFS for each vertex.