python 最短路径-贪婪算法

#!/usr/bin/python3.4
import copy
distance={(1,2):2,(1,3):1,(2,3):2,(2,4):1,(2,5):3,(3,4):4,(4,5):1,(3,6):3,(5,7):4,(6,7):1}
maxcount=7
stack=list()
dst=dict()
path=dict()
def Probe(sourcenode,desnode):
    if sourcenode==desnode: return
    stack.append(sourcenode)
    for i in range(1,maxcount+1):
        if (sourcenode,i) in distance.keys() and i not in stack:
            if (dst.get(sourcenode,0)+distance[(sourcenode,i)] < dst.get(i,1000)):
                dst[i]=dst.get(sourcenode,0)+distance[(sourcenode,i)]
                path[i]=sourcenode
    if sourcenode in dst.keys(): del dst[sourcenode]
    if not len(dst.keys()): return True
    item=sorted(dst.items(),key=lambda d:d[1])[0][0]
    Probe(item,desnode)
def searchPath(sourcenode,desnode):
   if sourcenode == desnode : return
   if desnode in path.keys():
        searchPath(sourcenode,path[desnode])
        print('path %d->%d'%(path[desnode],desnode))
Probe(2,7)
print(path)
searchPath(2,6)


Probe为生成路径信息

searchPath(s,d) 为打印最短路径

本例输出为:

{3: 2, 4: 2, 5: 4, 6: 3, 7: 5}
path 2->3
path 3->6

从2->6的最短路径为: 先2到3,再3到6.





你可能感兴趣的:(python 最短路径-贪婪算法)