Algorithms: Design and Analysis, Part 1, Programming Assignment #5

import heapq
import sys

fname = 'dijkstraData.txt'
#fname = "tc.txt"
fh = open(fname)
lines = [line.rstrip('\n') for line in fh]
# Generate graph as a list of dictionaries.
# Index of list is the vertex, value is a disctionary where key is the outgoing vertex and value is the length of the edge.
neighbor = []
d = dict()
neighbor.append(d)
for line in lines:
    part = line.split()
    v = int(part[0])
    d = dict()
    for i in part[1:]:
        values = map(int, i.split(','))
        d[values[0]] = values[1]
    neighbor.append(d)
# Generating graph ends

# Dijkstra
s = 1
dest = [7,37,59,82,99,115,133,165,188,197]
#dest = range(12)
res = []
# vertices processded so far in a dictionary
x = dict()
# Computed shortest path distances in a dictionary/heap
a = dict()
x[s] = 0
a[s] = 0
while len(x) != len(neighbor):
    f = False
    for v in x.keys():
        for w, e in neighbor[v].items():
            if w in x:
                continue
            f = True
            cur = a[v] + e
            if w in a:
                a[w] = min(cur, a[w])
            else:
                a[w] = cur
            #print "v:a[%d]:%d, e:%d, w:a[%d]:%d" % (v, a[v], e, w, a[w])
    if f:
        min_e = sys.maxint
        min_v = 0
        for w, e in a.items():
            if (w not in x) and (e < min_e):
                min_e = e
                min_v = w
        x[min_v] = min_e
        #print "x[%d]:%d" % (min_v, x[min_v])
    else:
        for w, e in a.items():
            x[w] = e
        #print "exit"
        break
    #print "end of loop, a", a

for d in dest:
    res.append(x.get(d, 0))
print res

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值