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])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值