Algorithm/lanqiao/test/2019省最短路.py

60 lines
1.2 KiB
Python
Raw Normal View History

2022-04-09 01:07:54 +08:00
map_in = [
['A', 'E', 1],
['A', 'B', 2],
['A', 'C', 1],
['A', 'D', 1],
['A', 'E', 1],
['B', 'G', 1],
['B', 'J', 2],
['C', 'D', 3],
['C', 'G', 3],
['C', 'F', 3],
['D', 'G', 2],
['D', 'H', 1],
['D', 'I', 2],
['E', 'H', 1],
['E', 'I', 3],
['F', 'J', 1],
['F', 'G', 1],
['G', 'K', 2],
['G', 'I', 3],
['H', 'L', 2],
['H', 'I', 1],
['I', 'M', 3],
['J', 'S', 2],
['K', 'N', 1],
['K', 'L', 3],
['L', 'R', 1],
['L', 'M', 1],
['M', 'N', 2],
['M', 'Q', 1],
['M', 'S', 1],
['N', 'P', 1],
['Q', 'O', 1],
['O', 'R', 3],
['P', 'O', 1],
['R', 'S', 1],
]
# 点的数量 数出来的
n = 19
# 初始化图 到自身到距离为0
fig = [[float('inf')] * n for _ in range(n)]
for i in range(n):
fig[i][i] = 0
# 构建好路 每个节点之间的距离
for src, dst, dis in map_in:
src, dst = ord(src) - ord('A'), ord(dst) - ord('A')
fig[src][dst] = fig[dst][src] = dis
# 从起点到每个节点到距离 S为最后一个节点 因为是字母序排序的
dis = [float('inf')] * n
dis[0] = 0
for i in range(n):
for j in range(n):
dis[j] = min(dis[j], dis[i] + fig[i][j])
print(dis)
print(dis[-1])