In the networkx there is such a function
nx.all_simple_paths(G,source=0,target=5)
it returns all the paths, but if there are a lot of possible paths, it will work very long.
How can one immediately get just any path?
In the networkx there is such a function
nx.all_simple_paths(G,source=0,target=5)
it returns all the paths, but if there are a lot of possible paths, it will work very long.
How can one immediately get just any path?
It does not produce all paths, it returns a generator that may be exhausted to obtain all paths. The distinction is not nit-picky: it is precisely how we can answer your question. From the documentation, all_simple_paths
already uses a depth-first search (this is what you want). We can then do the following,
path = next(nx.all_simple_paths(G, source=0, target=5))
Which will raise a StopIteration
if no path exists. See also here for more details.
For example:
import networkx as nx
import random
G = nx.complete_graph(4)
paths = list(nx.all_simple_paths(G, source=0, target=3))
print paths
# [[0, 1, 2, 3], [0, 1, 3], [0, 2, 1, 3], [0, 2, 3], [0, 3]]
# get a random idx
idx = random.randint(0, len(paths))
print paths[idx]
# [0, 3] may be
# print all path it
for path in paths:
print path