分支限界法---旅行售货员问题

N: int = 4
MAX_WEIGHT: int = 4000
NO_PATH: int = -1
City_Graph = [[int('0')] * (N+1) for _ in range(N+1)]  # 初始化dp
x = [int('0') * (N+1) for _ in range(N+1)]  # 保存第i步便利的城市
isIn = [int('0') * (N+1) for _ in range(N+1)]  # 保存城市i是否已加入路径
bestx = [int('0') * (N+1) for _ in range(N+1)]  # 最优路径


def Travel_Backtrack(t: int):
    global bestw, cw
    if t > N:  # 走完了,输出结果
        for i in range(1, N+1):  # 输出当前路径
            print(x[i], end=" ")
        print()
        if cw < bestw:
            for i in range(1, N + 1):
                bestx[i] = x[i]
            bestw = cw
        return
    else:
        for j in range(1, N+1):
            if City_Graph[x[t - 1]][j] != NO_PATH and (not isIn[j]):  # 能到而且没有加入到路径中
                isIn[j] = 1
                x[t] = j
                cw = cw + City_Graph[x[t - 1]][j]
                Travel_Backtrack(t+1)
                isIn[j] = 0
                x[t] = 0
                cw = cw - City_Graph[x[t - 1]][j]


if __name__ == '__main__':
    City_Graph[1][1] = NO_PATH
    City_Graph[1][2] = 30
    City_Graph[1][3] = 6
    City_Graph[1][4] = 4

    City_Graph[2][1] = 30
    City_Graph[2][2] = NO_PATH
    City_Graph[2][3] = 5
    City_Graph[2][4] = 10

    City_Graph[3][1] = 6
    City_Graph[3][2] = 5
    City_Graph[3][3] = NO_PATH
    City_Graph[3][4] = 20

    City_Graph[4][1] = 4
    City_Graph[4][2] = 10
    City_Graph[4][3] = 20
    City_Graph[4][4] = NO_PATH
    # print(City_Graph)
    for i in range(1, N+1):
        x[i] = 0
        bestx[i] = 0
        isIn[i] = 0
    x[1] = 1  # 第一步走城市1
    isIn[1] = 1  # 第一个城市加入路径
    bestw = MAX_WEIGHT  # 最优路径总权值
    cw = 0  # 当前路径总权值

    Travel_Backtrack(2)  # 从第二步开始选择城市
    print("最优值为", bestw)
    print("最优解为:")
    for i in range(1, N+1):
        print(bestx[i], end=" ")
    print()

    原文作者:分支限界法
    原文地址: https://blog.csdn.net/securiry/article/details/85162495
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞