I am using igraph (Python) and would like to get all possible paths between two nodes in a directed graph. I am aware of the function get_all_shortest_paths
, wh
I can not be sure, but looking for a couple of minutes in python igraph documentation it looks like such a function does not exist. I stopped looking because in my opinion such information is not really useful, and at least if I would be a developer, I would not create it. Back to the question:
First of all you need to understand that for an arbitrary graph, the number of such paths would be infinite. All you need is one cycle and you can create infinite amount of paths. So in order for this number to be finite it should be directed acyclic graph.
So if you have a DAG, you can use DFS and recursively calculate all the paths (note that you will end up with exponential graph and most probably will not be able to find an answer in the reasonable time for even for a reasonably big graph). I was not writing the code by myself, and just googled a little bit and it looks like this guy have done what you want (basically he is doing DFS).
from igraph import *
def adjlist_find_paths(a, n, m, path=[]):
"Find paths from node index n to m using adjacency list a."
path = path + [n]
if n == m:
return [path]
paths = []
for child in a[n]:
if child not in path:
child_paths = adjlist_find_paths(a, child, m, path)
for child_path in child_paths:
paths.append(child_path)
return paths
def paths_from_to(graph, source, dest):
"Find paths in graph from vertex source to vertex dest."
a = graph.get_adjlist()
n = source.index
m = dest.index
return adjlist_find_paths(a, n, m)
I have not checked whether it produces correct result.