It's me trying to understand recursion, the graph is here as support to help me ask my question.
I have this graph :
And I'm using this function to find all the paths possible from one vertex to an other.
def find_all_path(self, start_vertex, end_vertex, path=[]):
graph = self.__graph_dict
path = path + [start_vertex]
if end_vertex == start_vertex:
return [path]
paths = []
for neighbour in graph[start_vertex]:
if neighbour not in path:
extended_paths = self.find_all_path(neighbour, end_vertex, path)
for p in extended_paths:
paths.append(p)
return paths
Which would give, from a
to d
:
[['a', 'b', 'd'], ['a', 'b', 'c', 'e', 'd'], ['a', 'b', 'c', 'e', 'f', 'd'], ['a', 'c', 'b', 'd'], ['a', 'c', 'e', 'd'], ['a', 'c', 'e', 'f', 'd']]
1. Is paths
passed by reference?
Meaning that, paths
is changing throughout each stack even though they're not related.
2. How does paths
gets all the path appended to it?
For example, a
has b
and c
as neighbours. Let's say it goes through b
first, path = [a,b]
, and then it calls the function again with (b,d,[a,b])
as parameters. It goes again until it reaches the base case where d == d
.
At this point, it returns [a,b,d]
and so forth until... what? The stack is empty, how does that work?
Obviously, that's the part I don't get, since paths
is returned to the top how come all the other path
can be appended to it?
Here's me trying to understand this stack appending process :
I think my confusion is related to the flow ("how does the computing process works?"). At first, I though it was the longest path which would be appended as the first element in paths
, meaning the process wouldn't end until the longest path is found, but it's not, since [a,b,d] is first.