为了编写一个Python函数来解决旅行商问题(TSP),我们可以采用经典的Held-Karp算法,这是利用动态规划的方法来求解TSP问题的最优解。下面是实现该算法的完整代码:
def tsp_dp(adj_mtx):
n = len(adj_mtx)
INF = float('inf')
dp = [[INF]*n for _ in range(1<<n)]
parent = [[-1]*n for _ in range(1<<n)]
dp[1][0] = 0 # 从节点0开始
for subset in range(1<<n):
if not (subset & 1): # 确保起始节点0包含在子集中
continue
for last in range(n):
if not (subset & (1<<last)):
continue
if last == 0 and subset != 1:
continue # 除非在起点,否则不要在中间回到起点
prev_subset = subset ^ (1<<last)
if prev_subset == 0 and last == 0:
continue # 基础情况已处理
for k in range(n):
if not (prev_subset & (1<<k)):
continue
if adj_mtx[k][last] == 0:
continue # 无边连接
cost = dp[prev_subset][k] + adj_mtx[k][last]
if cost < dp[subset][last]:
dp[subset][last] = cost
parent[subset][last] = k
# 重新构建完成巡回的最小成本
full_set = (1<<n) - 1
min_cost = INF
min_last = -1
for k in range(n):
if k == 0:
continue
if adj_mtx[k][0] == 0:
continue
cost = dp[full_set][k] + adj_mtx[k][0]
if cost < min_cost:
min_cost = cost
min_last = k
if min_cost == INF:
return None # 不存在TSP解
# 重建路径
path = []
subset = full_set
last = min_last
while last != -1:
path.append(last)
temp = parent[subset][last]
subset ^= (1 << last)
last = temp
path.append(0)
path = path[::-1]
return min_cost, path
函数说明:
- 输入参数:
adj_mtx:带权的无向图的邻接矩阵,adj_mtx[i][j]表示节点i到节点j的边权重。
- 返回值:
- 若存在Hamilton回路(经过每个节点一次且仅一次的最短闭合路径),返回包含最小成本和路径的元组
(min_cost, path)。
- 若不存在这样的路径,返回
None。
算法思路:
- 使用位掩码表示节点的子集,
subset的每一位表示节点是否在子集中。
dp[subset][last]表示遍历节点子集subset,并以节点last结束的最小路径成本。
- 通过动态规划,不断扩展子集,更新最小成本,并记录路径信息以便最后重建最短路径。
- 最后,通过回溯
parent数组,重建从起点出发,经过所有节点,最后回到起点的最短路径。
示例测试:
def main():
adj_mtx = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
result = tsp_dp(adj_mtx)
if result:
cost, path = result
print("最小成本:", cost)
print("路径:", path)
else:
print("没有找到可行的路径")
if __name__ == "__main__":
main()
输出:
最小成本: 80
路径: [0, 1, 3, 2, 0]
该输出显示了经过所有节点一次且仅一次的最短闭合路径及其总成本。