旅行商(TSP)问题,贪心法和动态规划法解答

import sys


# 贪心算法求解TSP,得到的为局部最优解
# 需要提前给出path_length, path_vertexs = [],[]
def find_path(start, n, end):
    path_vertexs.append(start)
    row = C[start]  # C为代价矩阵
    copy_row = row[:]
    for i in path_vertexs:  # 删除已走过的点(包括自身),有可能删除前面位置的点
        copy_row.remove(row[i])
    if len(path_vertexs) < n:
        min_length = min(copy_row)
        start = row.index(min_length)  # 若删除前面的点,则索引查找刚好为前面的点,所以没问题
        path_length.append(min_length)
        find_path(start, n, end)
    else:
        min_length = C[start][end]
        path_length.append(min_length)
        path_vertexs.append(end)
    return path_length, path_vertexs


# 动态规划方法,任意起点可得出全局最优解,时间复杂度O(n3)
def dp_tsp(n):
    dp = [[-1] * (1 << (n - 1)) for i in range(n)]  # 从0点开始出发
    for i in range(n):
        dp[i][0] = C[i][0]
    for j in range(1, 1 << (n - 1)):
        for i in range(n):
            dp[i][j] = sys.maxsize
            if i > 1:
                if ((j >> (i - 1)) & 1) == 1:  # j不包含i
                    continue
            for k in range(1, n):   # j包含k
                if (j >> (k - 1) & 1) == 0:
                    continue
                if dp[i][j] > C[i][k] + dp[k][j ^ (1 << k - 1)]:   # j去除k
                    dp[i][j] = C[i][k] + dp[k][j ^ (1 << k - 1)]
    return dp[0][-1]


if __name__ == '__main__':
    C = [[0, 2, 6, 5],
         [2, 0, 4, 4],
         [6, 4, 0, 2],
         [5, 4, 2, 0]]
    # 基于贪心算法,需要比较所有起点,为局部最优解
    print('不同起点出发,贪心法解答:')
    for i in range(len(C)):
        path_vertexs = []
        path_length = []
        start = end = i
        length, vertexs = find_path(start, len(C), end)
        # print(vertexs)
        # print(length)
        print(sum(length))
    # 基于动态规划,起点随意,均为最优解
    print('不同起点出发,动态规划解答:')
    for i in range(len(C)):
        temp_1 = C[i]
        C[i] = C[0]
        C[0] = temp_1
        for j in range(len(C)):
            temp_2 = C[j][0]
            C[j][0] = C[j][i]
            C[j][i] = temp_2
        res = dp_tsp(len(C))
        print(res)

参考:https://www.cnblogs.com/youmuchen/p/6879579.html

你可能感兴趣的:(数据结构与算法,数据结构与算法)