I have a depth-first search example code in python as below.
def DFS_paths_recursive(self, start, end, path = None):
if path == None:
path = [start]
if start == end:
yield path
else:
unvisited = set(self._graph_dic[start]) - set(path)
for vertex in unvisited:
yield from self.DFS_paths_recursive(vertex, end, path+[vertex])
But if I modify the code as below, the output is strange. What I did is just modifying the path before the recursive call in the last line. What is the problem?
def DFS_paths_recursive(self, start, end, path = None):
if path == None:
path = [start]
if start == end:
yield path
else:
unvisited = set(self._graph_dic[start]) - set(path)
for vertex in unvisited:
path.append(vertex)
yield from self.DFS_paths_recursive(vertex, end, path)
For example, for the graph g = { "a" : ["d"], "b" : ["c"], "c" : ["b", "c", "d", "e"], "d" : ["a", "c", "e"], "e" : ["c"], "f" : ["g"], "g" : ["f"] }
Sometimes the output of paths between "a" and "e" is ['a', 'd', 'c', 'b', 'e'],['a', 'd', 'c', 'b', 'e', 'e']
, and sometimes the output becomes ['a', 'd', 'e']
.