python解决最短路径问题:Floyd-Warshall算法

昨晚做的华为实习生笔试题第三题的解答就涉及到最短路径问题,今天查阅资料l,重新做了一下。

主要思路:

1.根据天气状况更新路线图hmap

2.根据最新的路线图hmap,运用最短路径算法Floyd-Warshall算法,求得任意两城市之间最短路径所必须经过的城市,放在path矩阵中(A矩阵存放对应的权值)

3.然后编写一个函数getRoutes(path,start,end),根据指定的起始点和终点获得路径。

代码:

#coding= utf-8
#最短路径问题:能到X的所有城市(除去自身),找到时间最小对应的城市M,然后找5到M的时间最小对应的城市,不断递推
#大雾城市:不可从该城市出发,也不可到达该城市,对应行列时间为1000
#从城市5出发到达任意城市的最短时间对应的路径,及

#根据大雾城市设置新的map,y中存放的为大雾城市列表
from collections import defaultdict
from heapq import *
'''
def dijkstra_raw(edges, from_node, to_node):
    g = defaultdict(list)
    for l,r,c in edges:
	g[l].append((c,r))
    q, seen = [(0,from_node,())], set()
    while q:
	(cost,v1,path) = heappop(q)
	if v1 not in seen:
	    seen.add(v1)
	    path = (v1, path)
            if v1 == to_node:
                return cost,path
            for c, v2 in g.get(v1, ()):
		if v2 not in seen:
		    heappush(q, (cost+c, v2, path))
    return float("inf"),[]


def dijkstra(edges, from_node, to_node):
    len_shortest_path = -1
    ret_path=[]
    length,path_queue = dijkstra_raw(edges, from_node, to_node)
    if len(path_queue)>0:
        len_shortest_path = length		## 1. Get the length firstly;
        ## 2. Decompose the path_queue, to get the passing nodes in the shortest path.
        left = path_queue[0]
	ret_path.append(left)		## 2.1 Record the destination node firstly;
	right = path_queue[1]
	while len(right)>0:
            left = right[0]
	    ret_path.append(left)	## 2.2 Record other nodes, till the source-node.
            right = right[1]
	    ret_path.reverse()	## 3. Reverse the list finally, to make it be normal sequence.
    return len_shortest_path,ret_path
'''
def setNewMap(y):
    t = [[0,2,10,5,3,1000],
            [1000,0,12,1000,1000,10],
            [1000,1000,0,1000,7,1000],
            [2,1000,1000,0,2,1000],
            [4,1000,1000,1,0,1000],
            [3,1000,1,1000,2,0]]
    if len(y) == 1 and y[0] == '0':
        return t
    #字符串变为int
    for i in xrange(len(y)):
        y[i] = int(y[i])
    #对应城市的行变为1000
    for i in xrange(len(y)):
        t[y[i]-1] = [1000,1000,1000,1000,1000,1000]
    #对应城市的列变为1000
    for i in xrange(6):
        for j in y:
            t[i][j-1] = 1000
    return t

#根据最短路径矩阵,输出两点之间对应的路线
def getRoutes(path,start,end): #最短路径矩阵
    rts = [] #存放路线
    rts.append(start)
    i = start-1
    while path[i][end-1] != -1:
        rts.append(path[i][end-1]+1)
        i = path[i][end-1]
    rts.append(end)
    return rts
#求最短路径:指定起点sn,终点en和地图tmp
def shortestPath(tmp):
    A = tmp
    path= [] #存放到某点必须经过的路径点
    for i in xrange(6):
        path.append([-1,-1,-1,-1,-1,-1])
    for k in xrange(6):
        for i in xrange(6):
            for j in xrange(6):
                if A[i][j] > A[i][k] + A[k][j]:
                    A[i][j] = A[i][k] + A[k][j]
                    path[i][j] = k
    print 'A:%s'%(A)
    print 'path:%s'%(path)
    return A,path

hmap = [[0,2,10,5,3,1000],
        [1000,0,12,1000,1000,10],
        [1000,1000,0,1000,7,1000],
        [2,1000,1000,0,2,1000],
        [4,1000,1000,1,0,1000],
        [3,1000,1,1000,2,0]]
'''
lines = [] #存放最短路径
#目的城市
X = raw_input()
#大雾城市,多个大雾城市时以,分割
Y = []
while True:
    ins = raw_input()
    if not ins:
        break
Y = ins.split(',')

#更新当前路径地图
tmp = setNewMap(Y)
'''
Y = [4]
tmp = setNewMap(Y)
a,path = shortestPath(tmp)
rts = getRoutes(path,5,2)
print rts
运行结果:



这一个测试用例通过了。

总结:

分析问题,剖析出对应的算法,稍加改造运行实现。



最短路径算法参考链接:

http://www.cnblogs.com/biyeymyhjob/archive/2012/07/31/2615833.html

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值