I'm writing a dfs code like below:
def dfs(self, graph, node, path):
if node==len(graph)-1:
self.res.append(path)
else:
for i in graph[node]:
path.append(i)
self.dfs(graph, i, path)
print(path.pop())
but got undesired result, while I changed the for loop code in dfs to:
self.dfs(graph, i, path+[i])
the result is what I want. But I could not figure out what's the difference of these 2 piece codes. Thanks
Algorithm-wise, I need more information about how you represent the graph to give more insight. But code-wise, the difference is caused by the fact that List in Python is mutable . That means in your original code, when you pop
the path
list, the entry in the res
will change accordingly. Check this by the following.
a = [1,2,3]
b = []
b.append(a) # b = [[1,2,3]]
a.pop() # now b = [[1,2]]
But when you change the argument to path + [i]
, a new List is constructed, ie the path
inside the next recursive call of dfs
is decoupled from that in the previous one. Check this by the following.
a = [1,2]
b = []
b.append(a+[3]) # b = [[1,2,3]]
a.pop()
# b is still [[1,2,3]], because the expression a + [3] will be evaluated to another List
Te original version mutates path in each iteration of each recursion. The second version just makes a copy and adds an extra element. This copy is not bound to a name, it just get passed to the next level of recursion.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.