python解決圖的最短路徑問題

  遇到一個算法題目,描述以下: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()
相關文章
相關標籤/搜索