1 N: int = 4 2 MAX_WEIGHT: int = 4000 3 NO_PATH: int = -1 4 City_Graph = [[int('0')] * (N+1) for _ in range(N+1)] # 初始化dp 5 x = [int('0') * (N+1) for _ in range(N+1)] # 保存第i步便利的城市 6 isIn = [int('0') * (N+1) for _ in range(N+1)] # 保存城市i是否已加入路径 7 bestx = [int('0') * (N+1) for _ in range(N+1)] # 最优路径 8 9 10 def Travel_Backtrack(t: int): 11 global bestw, cw 12 if t > N: # 走完了,输出结果 13 for i in range(1, N+1): # 输出当前路径 14 print(x[i], end=" ") 15 print() 16 if cw < bestw: 17 for i in range(1, N + 1): 18 bestx[i] = x[i] 19 bestw = cw 20 return 21 else: 22 for j in range(1, N+1): 23 if City_Graph[x[t - 1]][j] != NO_PATH and (not isIn[j]): # 能到而且没有加入到路径中 24 isIn[j] = 1 25 x[t] = j 26 cw = cw + City_Graph[x[t - 1]][j] 27 Travel_Backtrack(t+1) 28 isIn[j] = 0 29 x[t] = 0 30 cw = cw - City_Graph[x[t - 1]][j] 31 32 33 if __name__ == '__main__': 34 City_Graph[1][1] = NO_PATH 35 City_Graph[1][2] = 30 36 City_Graph[1][3] = 6 37 City_Graph[1][4] = 4 38 39 City_Graph[2][1] = 30 40 City_Graph[2][2] = NO_PATH 41 City_Graph[2][3] = 5 42 City_Graph[2][4] = 10 43 44 City_Graph[3][1] = 6 45 City_Graph[3][2] = 5 46 City_Graph[3][3] = NO_PATH 47 City_Graph[3][4] = 20 48 49 City_Graph[4][1] = 4 50 City_Graph[4][2] = 10 51 City_Graph[4][3] = 20 52 City_Graph[4][4] = NO_PATH 53 # print(City_Graph) 54 for i in range(1, N+1): 55 x[i] = 0 56 bestx[i] = 0 57 isIn[i] = 0 58 x[1] = 1 # 第一步走城市1 59 isIn[1] = 1 # 第一个城市加入路径 60 bestw = MAX_WEIGHT # 最优路径总权值 61 cw = 0 # 当前路径总权值 62 63 Travel_Backtrack(2) # 从第二步开始选择城市 64 print("最优值为", bestw) 65 print("最优解为:") 66 for i in range(1, N+1): 67 print(bestx[i], end=" ") 68 print()