簡體   English   中英

Dijkstra 算法 Python

[英]Dijkstra's algorithm Python

給定一個圖和圖中的一個源頂點,找到從源到給定圖中所有頂點的最短路徑。 在這里閱讀更多-> 鏈接

請通過我的代碼 go 並通過指出我的邏輯有什么問題來幫助我。

我的代碼:

from collections import defaultdict

global INT_MAX
INT_MAX = 3 ** 38


class Graph:
    def __init__(self, numofVertices):
        self.vertList = defaultdict(list)
        self.numofVertices = numofVertices

    def addEdge(self, u, v, cost):
        self.vertList[u].append((v, cost))
        self.vertList[v].append((u, cost))

    def minDist(self, dist, visited):
        
        for v in range(self.numofVertices):
            if dist[v] < INT_MAX and v not in visited:
                minIndex = v
        return minIndex

    def dijsktra(self, src):
        dist = [INT_MAX] * self.numofVertices
        dist[src] = 0
        visited = set()

        for _ in range(self.numofVertices):
            minVertex = self.minDist(dist, visited)

            visited.add(minVertex)

            for nbr, edgeCost in self.vertList[minVertex]:
                if dist[nbr] > dist[minVertex] + edgeCost and nbr not in visited:
                    dist[nbr] = dist[minVertex] + edgeCost
        return dist


g = Graph(9)
g.addEdge(0, 1, 4)
g.addEdge(0, 7, 8)
g.addEdge(1, 7, 11)
g.addEdge(7, 8, 7)
g.addEdge(7, 6, 1)
g.addEdge(7, 1, 11)
g.addEdge(1, 2, 8)
g.addEdge(2, 3, 7)
g.addEdge(2, 5, 4)
g.addEdge(2, 8, 2)
g.addEdge(6, 8, 6)
g.addEdge(6, 5, 2)
g.addEdge(5, 2, 4)
g.addEdge(5, 3, 14)
g.addEdge(5, 4, 10)
g.addEdge(3, 4, 9)
print(g.dijsktra(0))

當前 Output:

[0, 4, 15, 25, 21, 11, 9, 8, 15] # Index represents the vertex

預計 Output

[0, 4, 12, 19, 21, 11, 9, 8 ,14]

這是我們正在解決的圖表: 在此處輸入圖像描述

問題出在檢查最小距離的 function 上,我們需要更新當前的最大值,以便我們可以將其與其他未訪問的頂點進行比較,並查看是否存在另一個具有較小值的頂點。

def minDist(self, dist, visited):
    max1 = 3 ** 38
    minIndex = 0
    for v in range(self.numofVertices):
        if dist[v] < max1 and v not in visited:
            max1 = dist[v]
            minIndex = v
    return minIndex

minDist方法有錯誤。 它返回第一個相鄰索引的索引,而不是距離最小的索引。

這個 function 應該如下所示:

def minDist(self, dist, visited):
    m = INT_MAX
    for v in range(self.numofVertices):
        if dist[v] < m and v not in visited:
            m = dist[v]
            minIndex = v 
    return minIndex

另外,我不確定您是否必須在 addEdge 中同時分配vertList[u]addEdge vertList[v]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM