I am writing a recursive DFS approach to find every path from 0 to (n-1) in a directed acyclic graph of n nodes given a list 'graph' where graph[i] is a list of all vertices that graph[i] can visit.
Here is my code:
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
end = len(graph)-1
ans = []
def dfs(path, node):
if node == end:
return path + [end]
path = path + [node]
for i in graph[node]:
potentialAns = dfs(path, i)
if potentialAns:
ans.append(potentialAns)
return None
dfs([], 0)
return ans
where if I change path = path + [node]
to path.append(node)
, behavior changes. For debugging purposes, given an input [[1,2],[3],[3],[]]
, after inserting print(path)
before the for loop, using the former list extension method results in:
stdout: [0] [0, 1] [0, 1, 2] and a wrong answer of [[0,1,3],[0,1,2,3]]
Given the same input and print statement, using the latter list extension method results in:
stdout: [0] [0, 1] [0, 2] and the correct answer of [[0,1,3],[0,2,3]]
I am curious as to why this is; I believe that it may have something to with underlying behaviors of the two list extension methods.