I'm fairly new in 'recursive functions'. So, I'm trying to wrap my head around why we use recursive functions and how recursive functions work and I think I've a fairly good understanding about it.
Two days ago, I was trying to solve the shortest path problem. I've a following graph(it's in python):
graph = {'a': ['b', 'c'],
'b': ['c', 'd'],
'c': ['d'],
'd': ['c'],
'e': ['f'],
'f': ['c']}
I'm just trying to find a path, not the shortest path.So, here is the code:
def find_path(graph,start,end,path=[]):
path = path + [start]
#Just a Test
print(path)
if start == end:
return path
if start not in graph:
return None
for node in graph[start]:
if node not in path:
new_path = find_path(graph,node,end,path)
if new_path:
#Just a test
print(path)
return new_path
print(find_path({'a':['b','c'],'b':['c','d'],'c':['d'],'d':['c'],'e':
['f'],'f':['c']},'a','d'))
My starting vertex is 'a' and the ending vertex is 'd'.
In the fourth line I just printed the 'path' to see where the path goes.
On line 17th I also printed the 'path', again just to test. And here is the result:
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
['a', 'b', 'c']
['a', 'b']
['a']
['a', 'b', 'c', 'd']
The first four lines of the result is the result of 'print(path)' on line 4 of the code. But, line 5th, 6th and 7th is the result of 'print(path)' on line 17th of the code.
My question is why the list of the path is decreasing by one vertex each time?
I've been trying to find it's solution for 2 days. I've went to forums, read the documentation about recursion and watched videos. But, no luck.
I would be greatful if somebody can answer.