我是 Python 的初学者,遇到这个问题已经有一段时间了。任何纠正问题的建议都是有价值的。下面是用于查找最短路径的代码,使用 Dijkstra 算法。我有成本矩阵和源作为输入。
def dijkstra(cost_matrix,source):
n = 20
dist = [0 for row in range(20)]
visited = [0 for row in range(20)]
for j in range(20):
visited[j] = "False"
visited[source] = "True"
for i in range(20):
dist[i] = cost_matrix[source][i]
prev_min = source
for k in range(20):
minimum = min(dist)
minimum2 = min(minimum,n)
for i in range(20):
if dist[i] > (cost_matrix[prev_min][minimum2] + cost_matrix[minimum2][i]):
dist[i] = cost_matrix[prev_min][minimum2] + cost_matrix[minimum2][i]
visited[minimum2] = "True"
prev_min = minimum2
return dist
计算 cost_matrix 的代码
def matrix():
k = 30
b_ij = [[0 for row in range(20)] for col in range(20)]
a_ij = [[0 for row in range(20)] for col in range(20)]
cost_matrix = [[0 for row in range(20)] for col in range(20)]
for i in range(20):
for j in range(20):
rand = random.randint(0,8)
b_ij[i][j] = rand
b_ij[j][i] = rand
while(k > 0):
rand1 = random.randint(0,19)
rand2 = random.randint(0,19)
a_ij[rand1][rand2] = 200
a_ij[rand2][rand1] = 200
k = k - 1
for i in range(20):
for j in range(20):
if a_ij[i][j] != 200:
rand = random.randint(0,8)
a_ij[i][j] = rand
a_ij[j][i] = rand
for i in range(len(a_ij)):
for j in range(len(b_ij[0])):
for k in range(len(b_ij)):
cost_matrix[i][j] += a_ij[i][k] * b_ij [k][j]
错误信息:
Traceback (most recent call last):
File "ass1.py", line 60, in <module>
print(dijkstra(cost_matrix, 1))
File "ass1.py", line 45, in dijkstra
dist[i] = cost_matrix[source][i]
TypeError: 'NoneType' object is not subscriptable