Dijkstra algorithm in Python3.5

#!/usr/bin/env python3
# Refer to: http://wiki.jikexueyuan.com/project/easy-learn-algorithm/dijkstra.html
# Comments: The Dijkstra algorithm can tell what is the shortest path and how much it cost.

cnt = 1         # ignore the first vertex
N = 6           # number of total vertex
original = 1000 # init cost of unconnected vertex with an infinity

 # map in 2D grid to connect vertex with positive cost
cost = [[0, 1, 12, original, original, original],
               [original, 0, 9, 3, original, original],
               [original, original, 0, original, 5, original],
               [original, original, 4, 0, 13, 15],
               [original, original, original, original, 0, 4],
               [original, original, original, original, original, 0]]
minimum_cost = cost[0]

# vertex to be calculated and shortest path from original
P_Q = [1, 0, 0, 0, 0, 0]
shortest_path = [[1], [2], [3], [4], [5], [6]]

while cnt < N:
    # take nearest vertex
    min_idx = -1
    min_node = 2000
    for i in range(N):
        if (P_Q[i] == 0) and (minimum_cost[i] < min_node):
            min_idx = i
            min_node = minimum_cost[i]
    P_Q[min_idx] = 1

    # calculate min vertex cost and get the nearest path
    path = shortest_path[min_idx]
    for j in range(N):
        if (P_Q[j] == 0):
            if (min_node + cost[min_idx][j] < minimum_cost[j]):
                minimum_cost[j] = min_node + cost[min_idx][j]
                shortest_path[j] = [] # empty path first at different middle vertex
                shortest_path[j].insert(1, j + 1)
                for p in range(0, len(path)):
                    shortest_path[j].insert(-1, path[p])
    cnt = cnt + 1

print("minimum cost: \n", minimum_cost)
print("shortest path:")
for n in range(N):
    shortest_path[n].insert(0, 1)
    print(shortest_path[n])

猜你喜欢

转载自blog.csdn.net/cutelily2014/article/details/82221102