我的无向图Dijkstra算法有什么问题?

2024-09-28 20:16:07 发布

您现在位置:Python中文网/ 问答频道 /正文

无向图dijkstra算法。给定起始节点,返回一个表,该表映射从a到每个节点的最短路径及其值

from heapq import heappush, heappop

def dijkstra(edges, start):

    graph = {}
    for (x, y, z) in edges:
        # A: [('B', 6)]
        graph[x] = graph.get(x, []) + [(y, z)]
        graph[y] = graph.get(y, []) + [(x, z)] # undirected graph
    
    
    table = {}
    for v in graph:
        table[v] = (float("inf"), None) # inf, no previous node
    table[start] = (0, None)
    stack = [(0, start)]
    
    visited = []
    while(stack != []):
        fill, node = heappop(stack)
        w = table[node][0]
        if(node in visited):
            continue
    
        visited.append(node)
        for (v, weight) in graph[node]:
            
            
            cur_weight, prev = table[v]
            if(cur_weight > weight + w):
                table[v] = (weight + w, node)
                
            cur_weight, prev = table[v]   
            heappush(stack, (cur_weight, v))
            
    return table           

edges = [['A', 'C', 1], ['C', 'E', 1], ['E', 'B', 1], ['A', 'B', 10]]
    
print(dijkstra(edges, 'A')) # outputs the correct table

上面的表的输出是正确的,但是对于非常大的输出,如(n=5000),它似乎失败了,我不确定为什么


Tags: innodefor节点stacktablestartgraph
1条回答
网友
1楼 · 发布于 2024-09-28 20:16:07

将堆栈交换为minheap以防止出现评论中提到的测试用例

from heapq import heappush, heappop

def dijkstra(edges, start):

    graph = {}
    for (x, y, z) in edges:
        # A: [('B', 6)]
        graph[x] = graph.get(x, []) + [(y, z)]
        graph[y] = graph.get(y, []) + [(x, z)] # undirected graph
    
    
    table = {}
    for v in graph:
        table[v] = (float("inf"), None) # inf, no previous node
    table[start] = (0, None)
    stack = [(0, start)]
    
    visited = set()
    while(stack != []):
        w, node = heappop(stack)
        if(node in visited):
            continue
    
        visited.add(node)
        for (v, weight) in graph[node]:
            
            
            cur_weight, prev = table[v]
            if(cur_weight > weight + w):
                table[v] = (weight + w, node)          
                heappush(stack, (weight + w, v))
            
    return table

编辑:根据下面的评论对其进行了优化

相关问题 更多 >