我使用嵌套的字典來指示圖的頂點和邊,如:錯誤的遞歸函數來尋找可能的路線的數量
[
A: [B,D,E],
B: [C],
C: [D,E],
D: [C,E],
E: [B]
]
這是我到目前爲止的代碼:
def number_of_trips(self, start_point, end_point, maxstops):
return self._find_path(start_point, end_point, 0, 0, maxstops)
def _find_path(self, point_a, end_point, current_stops, routes, maxstops):
current_stops += 1
if current_stops > maxstops:
return routes
if end_point in self.digraph[point_a]:
return routes + 1
else:
for x in self.digraph[point_a]:
return self._find_path(x, end_point, current_stops, routes, maxstops)
return routes
並且該方法被稱爲像這樣:
number_of_trips('C', 'C', 3)
,其輸出1,而不是2
我的遞歸函數有什麼問題?
我認爲你應該以某種方式從明年遞歸總結了所有的路線,而不是'返回「它們。在你的'else'分支中,你將在你的第一個'x'處'返回'而不是循環所有'self.digraph [point_a]'。 – Luca
永遠不會更新'routes'的值! – hjpotter92