迪杰斯特拉(Dijkstra)算法Python实现

迪杰斯特拉(Dijkstra)算法(Python)

import numpy as np


def Input_Fun():
    n = int(input().strip())
    weight = []
    for i in range(n):
        temp = input().split(' ')
        for j in temp:
            weight.append(int(j))
    weights = np.array(weight).reshape(n, n)
    print(n)
    print(weights)
    return n, weights


def Result_Output(prev, i):
    if prev[i] != 0:
        Result_Output(prev, prev[i])
        print('->{}'.format(prev[i]+1), end='')


def Dijkstra():
    n, weights = Input_Fun()
    flag = np.zeros(n, bool)  # 设置标志,确认是否加入集合
    dist = weights[0]  # 记录第0点到各个位置的距离
    prev = np.zeros(n, int)  # 记录节点的前一个位置
    for i in range(n - 1):  # 进行n-1次迭代,每次加入一个点
        temp = float('inf')
        u = 0
        for j in range(n):
            if not flag[j] and dist[j] < temp and dist[j] != 0:  # 该点不在集合内、距离小、有连接
                u = j
                temp = dist[j]
        flag[u] = True
        for j in range(n):
            if not flag[j] and weights[u][j] != 0:
                if dist[u] + weights[u][j] < dist[j] or dist[j] == 0:
                    dist[j] = dist[u] + weights[u][j]
                    prev[j] = u
    for i in range(n - 1):
        print(dist[i + 1], ':1', end='')
        Result_Output(prev, i+1)
        print("->{}".format(i + 2))


if __name__ == '__main__':
    Dijkstra()

你可能感兴趣的:(提高)