Reputation: 1
This Code prints all Paths in a Graph from startNode to destinationNode.
I copied it from https://www.geeksforgeeks.org/find-paths-given-source-destination/ and modified it slightly. The Code works perfectly fine, but i need the paths to be returned instead of printed, but don't get how to do that.
If I add return to printAllPathsUtil(i, d, unvisited, path)
it only returns one of the paths.
I am not that good at recursion and don't know what to do now.
async def getAllPathsUtil(s, d, unvisited, path):
unvisited.append(s)
path.append(s)
if s == d:
path
else:
for i in (await children(s)):
if not(i in unvisited):
await getAllPathsUtil(i, d, unvisited, path)
path.pop()
unvisited.remove(s)
async def printAllPaths(startNode, destinationNode):
all_paths = await getAllPathsUtil(startNode, destinationNode, [], [])
print(all_paths)
Upvotes: 0
Views: 80
Reputation: 2045
If you want to keep your recursive algorithm, than using yield
might be the simplest option.
def graph_paths(s, d, visited, path):
visited.append(s)
path.append(s)
if s == d:
yield path
else:
for i in children(s):
if i not in visited:
yield from graph_paths(i, d, visited, path)
path.pop()
visited.remove(s)
def print_graph_paths(start_node, dest_node):
for path in graph_paths(start_node, dest_node, [], []):
print(path)
But as a better approach I recommend to replace a recursion calls by the stack, it will neutralize the maximum recursion depth problem.
Upvotes: 1