此代碼在python official essays on graph theory中給出。這裏的代碼:這個Python代碼是否使用深度優先搜索(DFS)來查找所有路徑?
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if not graph.has_key(start):
return []
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
我不擅長python,因爲我還沒有足夠的練習和閱讀。您能否通過將此與DFS圖中的同胞概念相關聯來解釋代碼?謝謝。
'paths.extend(newpaths)' – 2010-11-20 02:25:59
作爲參考,我總是會'不在圖中開始而不是在'無圖。 has_key(start)'(我假設'graph'是一個'dict'或類似的)。 – 2010-11-20 02:27:18
克里斯,是的'圖'是一個'字典'。 – Pupil 2010-11-20 02:28:04