python解決圖的最短路徑問題


  遇到一個算法題目,描述如下:

  

  對圖結構有了解的不難發現,這是經典的求圖的最短路徑問題。以下是python代碼:

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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM