我正在尝试在Python中实现Held-Karp,但它似乎没有起作用。我的问题与经典TSP问题存在两个不同(如我在网络中找到的H-K算法的描述中所使用的): - 我不需要返回原始节点。我认为这被称为哈密顿循环,但我对图算法不是很熟悉,所以我不完全确定。每个城市都需要像TSP一样被访问过一次 - 图中的某些边缺失
我使用了networkx并创建了这个函数:
def hk(nodes,Graph,start_node, total_ops, min_weight = 9999999,min_result = []):
nodes.remove(start_node)
# removes the current node from the set of nodes
for next_node in nodes:
total_ops += 1
current_weight = 0
try:
current_weight += Graph[start_node][next_node]["weight"]
# checks if there's an edge between the current node and the next node
# If there's an edge, adds the edge weight
except:
continue
sub_result = []
if len(nodes) > 1:
new_nodes = set(nodes)
sub_result,sub_weight,total_ops = hk(new_nodes,Graph,next_node, total_ops)
#calculates the minimum weight of the remaining tree
current_weight += sub_weight
if current_weight < min_weight:
# if the weight of the tree is below the minimum weight, update minimum weight
min_weight = current_weight
min_result = [next_node] + sub_result
return min_result,min_weight,total_ops
但有些事情显然是错误的,因为我期待O(n ** 2 * 2 ** n)的复杂性,但我得到的是O(n!),与蛮力方法相同(逐一尝试所有组合) )。很明显,我的实施中存在错误。
谢谢。