I've been trying to understand depth first search, and using various sources online obtained the following code:
graph = {'A': ['B', 'D'], 'B': ['E'], 'C': [], 'D': ['C', 'E'],
'E': ['H', 'I', 'J'], 'F': [], 'G': [], 'H': ['F'],
'I': [], 'J': ['G']}
def dfs(graph, start, end, path=None):
if path == None:
path = []
path = path + [start]
paths = []
if start == end:
return [path]
for neighbour in graph[start]:
if neighbour not in path:
paths.extend(dfs(graph, neighbour, end, path))
return paths
print(dfs(graph, 'A', 'G'))
This outputs the desired result:
[['A', 'B', 'E', 'J', 'G'], ['A', 'D', 'E', 'J', 'G']]
But when I replace the line path = path + [start]
with path += [start]
(or path.extend([start])
, which I understand does the same thing) I get the following output: [['A', 'B', 'E', 'H', 'F', 'I', 'J', 'G', 'D', 'C']]
I know this is to do with a difference in the operations, but I don't really understand how it applies here. Please could someone explain this?