I was trying to solve 797. All Paths From Source to Target from Leetcode
.
I thought of using Backtracking with recursion.
In the below code, the list setOfPaths
is also getting updated when I pop from path
.
I am not sure what I am doing wrong here.
class Solution(object):
def allPathsSourceTarget(self, graph):
path=[]
setOfPaths=[]
path.append(0)
self.backtrack(graph,0,len(graph)-1,path,setOfPaths)
return setOfPaths
def backtrack(self,graph,src,dest,path,setOfPaths):
if(src == dest):
setOfPaths.append(path)
else:
for node in graph[src]:
path.append(node)
self.backtrack(graph,node,dest,path,setOfPaths)
path.pop(len(path)-1) #BackTracking