转换为适当的距离矩阵(对于TSP)

时间:2017-12-13 21:23:39

标签: python matrix traveling-salesman distance-matrix

我目前有一个这样的矩阵:

[[2, 6, 8, 9, 8, 6, 3], [4, 8, 10, 10, 7, 5], [5, 6, 8, 8, 9], [4, 6, 7, 8], [3, 5, 9], [3, 6], [4]]

这样第一个阵列是从城市1到2,3,4,5,6,7,8的距离,第二个是从城市2到3,4,5,6,7,8的距离......第7个数组是从城市7到城市8的距离。我需要将其转换为适当的距离矩阵。

到目前为止,我已插入0以使其大小为7,它变为:

[[2, 6, 8, 9, 8, 6, 3], [0, 4, 8, 10, 10, 7, 5], [0, 0, 5, 6, 8, 8, 9], [0, 0, 0, 4, 6, 7, 8], [0, 0, 0, 0, 3, 5, 9], [0, 0, 0, 0, 0, 3, 6], [0, 0, 0, 0, 0, 0, 4]]

然后我做了

for i,j if distance==0 then distances[i][j]=distances[j][i] 

它变成了:

[[2, 6, 8, 9, 8, 6, 3], [6, 4, 8, 10, 10, 7, 5], [8, 8, 5, 6, 8, 8, 9], [9, 10, 6, 4, 6, 7, 8], [8, 10, 8, 6, 3, 5, 9], [6, 7, 8, 7, 5, 3, 6], [3, 5, 9, 8, 9, 6, 4]]

然后插入0以包括从城市到同一城市的距离:

[[0, 2, 6, 8, 9, 8, 6, 3], [6, 0, 4, 8, 10, 10, 7, 5], [8, 8, 0, 5, 6, 8, 8, 9], [9, 10, 6, 0, 4, 6, 7, 8], [8, 10, 8, 6, 0, 3, 5, 9], [6, 7, 8, 7, 5, 0, 3, 6], [3, 5, 9, 8, 9, 6, 0, 4]]

最后添加了最终城市的距离:

[[0, 2, 6, 8, 9, 8, 6, 3], [6, 0, 4, 8, 10, 10, 7, 5], [8, 8, 0, 5, 6, 8, 8, 9], [9, 10, 6, 0, 4, 6, 7, 8], [8, 10, 8, 6, 0, 3, 5, 9], [6, 7, 8, 7, 5, 0, 3, 6], [3, 5, 9, 8, 9, 6, 0, 4], [3, 5, 9, 8, 9, 6, 4, 0]]

但我似乎在某个地方出了问题,因为我还没有制作出正确的距离矩阵。我相信它可能是距离[i] [j] = [j] [i]位,但我不完全确定。

3 个答案:

答案 0 :(得分:2)

这实际上是一种常见的形式,如果你能够使用python的优秀科学堆栈(这种方法需要numpy和scipy),这已经可用了:

import numpy as np
from scipy.spatial.distance import squareform

raw = np.array([[2, 6, 8, 9, 8, 6, 3], [4, 8, 10, 10, 7, 5], [5, 6, 8, 8, 9],
    [4, 6, 7, 8], [3, 5, 9], [3, 6], [4]])

print(squareform(np.hstack(raw)))  # use of hstack as some kind flattening here
                                   # many alternatives possible

输出:

[[ 0  2  6  8  9  8  6  3]
 [ 2  0  4  8 10 10  7  5]
 [ 6  4  0  5  6  8  8  9]
 [ 8  8  5  0  4  6  7  8]
 [ 9 10  6  4  0  3  5  9]
 [ 8 10  8  6  3  0  3  6]
 [ 6  7  8  7  5  3  0  4]
 [ 3  5  9  8  9  6  4  0]]

当然,这个function可以双向运作。

答案 1 :(得分:1)

这是在不需要导入的情况下解决问题的另一种方法。

data = [[2, 6, 8, 9, 8, 6, 3], [4, 8, 10, 10, 7, 5], [5, 6, 8, 8, 9], [4, 6, 7, 8], [3, 5, 9], [3, 6], [4]]
data.append([])
for city in range(len(data)):
    for missing in range(city):
        data[city].insert(missing, data[missing][city])
    data[city].insert(city, 0)
然后

data将包含:

[[0, 2,  6, 8, 9,  8,  6, 3],
 [2, 0,  4, 8, 10, 10, 7, 5],
 [6, 4,  0, 5, 6,  8,  8, 9],
 [8, 8,  5, 0, 4,  6,  7, 8],
 [9, 10, 6, 4, 0,  3,  5, 9],
 [8, 10, 8, 6, 3,  0,  3, 6],
 [6, 7,  8, 7, 5,  3,  0, 4],
 [3, 5,  9, 8, 9,  6,  4, 0]]

答案 2 :(得分:0)

我认为这有效:

d = [[2, 6, 8, 9, 8, 6, 3], [4, 8, 10, 10, 7, 5], [5, 6, 8, 8, 9], [4, 6, 7, 8], [3, 5, 9], [3, 6], [4]]

matrix = [0] * 8
for i in range(8):
    matrix[i] = [0] * 8

j = 0
for element in d:
    i = j
    for value in element:
        matrix[i+1][j] = value
        matrix[j][i+1] = value
        i += 1
    j += 1