Skip to content

Instantly share code, notes, and snippets.

@aleozlx
Created September 27, 2017 04:22
Show Gist options
  • Save aleozlx/aa0eb02373a396fb286557228bf44f8a to your computer and use it in GitHub Desktop.
Save aleozlx/aa0eb02373a396fb286557228bf44f8a to your computer and use it in GitHub Desktop.
def path_generator(G, a, b):
""" Find all paths from a to b in directed graph G """
assert all([0<=u<len(G) for u in [a,b]])
path = []
stack = [a]
while stack:
u = stack.pop()
if u<0: # this is backtrack
path.pop()
continue
else:
stack.append(-1) # backtrack trap
path.append(u)
if u==b:
yield path.copy()
continue # not interested in any path circles back here
stack.extend(G[u]-set(path))
G = [set([1,2]), set([3]), set([3]), set([4,5]), set([6,7]), set([6,8]), set(), set(), set()]
# Should find 4 paths
for p in path_generator(G, 0, 6):
print(p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment