这可以在 O(n) 时间内完成,其中 n 是节点数。解决方案是递归的:
要恢复路径,只需从函数中返回成本和路径即可。递归情况必须用当前节点扩展路径。
总运行时间为 O(n),因为为内部节点完成的非递归工作与子节点的数量成正比。运行时间无法渐近改善,但可以在实践中使用branch-and-bound algorithm 进行优化,该branch-and-bound algorithm 跟踪迄今为止成本最低的路径,并拒绝超过它的路径。
这是一个 Python 示例:
class Node:
def __init__(self, cost, children=()):
self.cost = cost
self.children = children
def __repr__(self):
return 'Node({})'.format(self.cost)
root = Node(1, (
Node(2, (
Node(5, (Node(9),)),
Node(6, (Node(9),)),
Node(9),
)),
Node(3, (
Node(8, (Node(9),)),
Node(9),
)),
Node(4, (Node(9),)),
))
def min_cost_path(node):
if not node.children:
return [node], node.cost
else:
# list of (path, cost) pairs
options = [min_cost_path(c) for c in node.children]
path, cost = min(options, key=lambda option: option[1])
path.append(node)
return path, cost + node.cost
例子:
>>> path, cost = min_cost_path(root)
>>> path
[Node(9), Node(2), Node(1)]
>>> cost
12
注意路径是以相反的顺序返回的。