以下のように、Pythonで深さ優先検索のサンプルコードがあります。
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])
しかし、コードを次のように変更すると、出力が奇妙になります。私がしたことは、最後の行の再帰呼び出しの前にパスを変更しただけです。何が問題ですか?
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)
たとえば、グラフのg = { "a" : ["d"], "b" : ["c"], "c" : ["b", "c", "d", "e"], "d" : ["a", "c", "e"], "e" : ["c"], "f" : ["g"], "g" : ["f"] }
場合、「a」と「e」の間のパス['a', 'd', 'c', 'b', 'e'],['a', 'd', 'c', 'b', 'e', 'e']
の出力が になることもあれば、出力が になることもあります['a', 'd', 'e']
。