python最短路径问题如何解决

发布时间:2022-05-27 15:27:04 作者:iii
来源:亿速云 阅读:206

这篇文章主要介绍“python最短路径问题如何解决”,在日常操作中,相信很多人在python最短路径问题如何解决问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”python最短路径问题如何解决”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

说明

1、最短路径问题是图论研究中的经典算法问题,用于计算从一个顶点到另一个顶点的最短路径。

2、最短路径问题有几种形式:确定起点的最短路径,确定终点的最短路径,确定起点和终点的最短路径,全局最短路径问题。

路径长度是将每个顶点到相邻顶点的长度记为1,而不是指两个顶点之间的道路距离——两个顶点之间的道路距离是连接边的权利。

实例

def findMin(row):
    minL = max(row)
    for i in row:
        if i != -1 and minL > i:
            minL = i
    return minL
def initRow(row, plus):
    r = []
    for i in row:
        if i != -1:
            i += plus
        r.append(i)
    return r
 
def getMinLen(table, e, t):
    count = len(table) - 1
    startPoint = 1
    #记录原点到各点最短距离 初始值为-1,即不可达
    lenRecord = list((-1 for i in range(count+1)))
    lenRecord[startPoint] = 0
    #记录每次循环的起点
    points = [startPoint]
    #已得到最短距离的点
    visited = set()
    while len(points)>0:
        #当前起点
        curPoint = points.pop()
        #原点到当前起点的距离
        curLen = lenRecord[curPoint]
        #当前起点到各点的距离
        curList = initRow(table[curPoint], t)
        #当前起点到各点的最短距离
        curMin = findMin(curList)
        visited.add(curPoint)
        idx = 0
        while idx<count:
            idx += 1
            #当前点不可达或到当前点的最短距离已计算出 则跳过
            if curList[idx] == -1 or idx in visited:
                continue
            #记录距离当前起点最近的点作为下次外层循环的起点
            if curList[idx] == curMin:
                points.append(idx)
            #如果从原点经当前起点curPoint到目标点idx的距离更短,则更新
            if lenRecord[idx] == -1 or lenRecord[idx] > (curLen+curList[idx]):
                lenRecord[idx] = curLen+curList[idx]
    return lenRecord[e]
 
def processInput():
    pointCnt, roadCnt, jobCnt = (int(x) for x in raw_input().split())
    table = []
    for i in range(pointCnt+1):
        table.append([-1] * (pointCnt+1))
    for i in range(roadCnt):
        (x, y, w) = (int(n) for n in raw_input().split())
        if table[x][y] == -1 or table[x][y] > w:
            table[x][y] = w
            table[y][x] = w
    res = []
    for i in range(jobCnt):
        e, t = (int(x) for x in raw_input().split())
        res.append(getMinLen(table, e, t))
    for i in res:
        print(i)
 
processInput()

到此,关于“python最短路径问题如何解决”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. 迷宫问题并求最短路径
  2. python实现Dijkstra算法的最短路径问题

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:怎么使用Perl语言下载基因组数据

下一篇:python的Bellman-Ford算法怎么使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》