forked from letangers/dijkstra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstra.py
executable file
·71 lines (54 loc) · 1.46 KB
/
dijkstra.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#构造图
def make_graph():
graph={}
f=open('data.txt')
a=f.read().split('\n')
f.close()
#处理文件中的数据
for b in a:
temp={}
#列表a的末尾可能有 “”
if b == '':
continue
c=b.split()
#在win下读取文件可能会出现这种情况
if '\xef\xbb\xbf' in c[0]:
c[0]=c[0].replace('\xef\xbb\xbf','')
#将c[0]的邻接点的信息存储在temp中
for i in range(1,len(c),2):
temp[c[i]]=c[i+1]
graph[c[0]]=temp
return graph
def dijkstra(begin,graph):
rea={}
#初始化距离数组m
m=[]
temp={}
for i in graph:
if i==begin:
continue
temp[i]=float('inf')
for i in range(len(graph)-1):
m.append(temp)
tmp=begin
for i in range(len(m)):
for j in graph[tmp]:
if j == begin:
continue
if i==0:
m[i][j]=graph[tmp][j]
m[i][j]=eval(m[i][j])
else:
m[i][j]=min(m[i-1][j],rea[tmp]+eval(graph[tmp][j]))
mmin=float('inf')
for mm in m[i]:
if m[i][mm]>0 and m[i][mm]<=mmin:
mmin=m[i][mm]
tmp=mm
rea[tmp]=m[i][tmp]
m[i][tmp]=-1
return rea
if __name__ == "__main__":
graph=make_graph()
result=dijkstra('a',graph)
print (result)