您的位置:首页 > 编程语言 > Go语言

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

2016-09-06 13:55 661 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: