我正在使用嵌套字典来指示图形的顶点和边缘,例如:
[
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。
我的递归函数有什么问题?
答案 0 :(得分:1)
在进行递归调用时递增routes
值:
return self._find_path(x, end_point, current_stops, routes + 1, maxstops)