我使用嵌套的字典来指示图的顶点和边,如:错误的递归函数来寻找可能的路线的数量
[
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