2

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?

2 Answers2

0

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.

Nelewout
  • 6,281
  • 3
  • 29
  • 39
-1

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
Jayhello
  • 5,931
  • 3
  • 49
  • 56
  • this does not answer the question, your solution includes first calling `nx.all_simple_paths` which is precisely what OP wanted to avoid – Inspi Dec 23 '20 at 08:33