python 图最短路径


<!-- lang: python -->
# -*- coding: utf-8 -*-
import itertools
import re
import math

def combination(lst):   #全排序
    lists=[]
    liter=itertools.permutations(lst)
    for lts in list(liter):
        lt=''.join(lts)
        lists.append(lt)
    return  lists

def coord(lst):     #坐标输入
    coordinates=dict()
    print u'请输入坐标:(格式为A:7 17)'
    p=re.compile(r"\d+")
    for char in lst:
        str=raw_input(char+':')
        dot=p.findall(str)
        coordinates[char]=[dot[0],dot[1]]
    print coordinates
    return coordinates

def repeat(lst):    #删除重复组合
    for ilist in lst:
        for k in xrange(len(ilist)):
            st=(ilist[k:],ilist[:k])
            strs=''.join(st)
            for jlist in lst:
                if(cmp(strs,jlist)==0):
                    lst.remove(jlist)
        for k in xrange(len(ilist)):
            st=(ilist[k:],ilist[:k])
            strs=''.join(st)
            for jlist in lst:
                if(cmp(strs[::-1],jlist)==0):
                    lst.remove(jlist)
        lst.append(ilist)
        print lst
    return lst

def count(lst,coordinates): #计算各路径
    way=dict()
    for str in lst:
        str=str+str[:1]
        length=0
        for i in range(len(str)-1):
            x=abs( float(coordinates[str[i]][0]) - float(coordinates[str[i+1]][0]) )
            y=abs( float(coordinates[ str[i] ][1]) - float(coordinates[ str[i+1] ][1]) )
            length+=math.sqrt(x**2+y**2)
        way[str[:len(str)-1]]=length
    return way

if __name__ =="__main__":
    print u'请输入图节点:'
    rlist=list(raw_input())
    coordinates=coord(rlist)

    list_directive = combination(rlist)
#    print "有方向完全图所有路径为:",list_directive
#    for it in list_directive:
#        print it
    print u'有方向完全图所有路径总数:',len(list_directive),"\n"

#无方向完全图
    list_directive=repeat(list_directive)
    list_directive=repeat(list_directive)
#    print "无方向完全图所有路径为:",list_directive
    print u'无方向完全图所有路径为:'
    for it in list_directive:
        print it
    print u'无方向完全图所有路径总数:',len(list_directive)

    ways=count(list_directive,coordinates)
    print u'路径排序如下:'
    for dstr in sorted(ways.iteritems(), key=lambda d:d[1], reverse = False ):
        print dstr
    raw_input()

你可能感兴趣的:(python 图最短路径)