I have a Directed Acyclic Graph (DAG), which consists of layers, with two subsequent layers being completely bipartite (much like a neural net), like the following:
I want to stream all paths in the DAG, in an iterative manner, via some generator, in a randomized order. Because, output must not be in order, textbook DFS approaches are out of question. Memory is an issue, so I don't want to store any paths that I have yielded before, except the DAG alone, which could be modified however is needed.
Example, the desired output for the above DAG is:
(1, 4, 6, 8)
(3, 4, 5, 8)
(2, 4, 7, 8)
(3, 4, 6, 8)
(1, 4, 5, 8)
(3, 4, 7, 8)
(1, 4, 7, 8)
(2, 4, 6, 8)
(2, 4, 5, 8)
instead of the following produced by DFS:
(1, 4, 5, 8)
(1, 4, 6, 8)
(1, 4, 7, 8)
(2, 4, 5, 8)
(2, 4, 6, 8)
(2, 4, 7, 8)
(3, 4, 5, 8)
(3, 4, 6, 8)
(3, 4, 7, 8)
Thanks for your help.
Update:
I have the following code
graph = {
1: set([4]),
2: set([4]),
3: set([4]),
4: set([5, 6, 7]),
5: set([8]),
6: set([8]),
7: set([8])
}
def dfs_paths(graph, start, goal):
stack = [(start, [start])]
while stack:
(vertex, path) = stack.pop()
for next in graph[vertex] - set(path):
if next == goal:
yield path + [next]
else:
stack.append((next, path + [next]))
def run_paths():
for start in [1, 2, 3]:
for path in dfs_paths(graph, start, 8):
print path
Finding all paths and then randomly streaming them will not work for me, as I do not want to store any paths I will be generating.