使用Python PriorityQueue实现Dijkstra算法结果错误如何排查
问题描述
使用Python的queue模块中的PriorityQueue类实现Dijkstra算法,在线判题平台运行时结果不符合预期,代码如下:
from queue import PriorityQueue class Solution: #Function to find the shortest distance of all the vertices #from the source vertex S. def dijkstra(self, V, adj, S): #code here q=PriorityQueue() distance=[-1]*V distance[S]=0 visited=set() visited.add(S) for i in adj[S]: distance[i[0]]=distance[S]+i[1] q.put([i[1],i[0]]) while not q.empty(): w,s=q.get() visited.add(s) for i in adj[s]: d=distance[s]+i[1] if distance[i[0]]==-1: distance[i[0]]=d elif distance[i[0]]>d: distance[i[0]]=d if i[0] not in visited: q.put([i[1],i[0]]) return distance #{ # Driver Code Starts #Initial Template for Python 3 import atexit import io import sys if __name__ == '__main__': test_cases = int(input()) for cases in range(test_cases): V,E = map(int,input().strip().split()) adj = [[] for i in range(V)] for i in range(E): u,v,w = map(int,input().strip().split()) adj[u].append([v,w]) adj[v].append([u,w]) S=int(input()) ob = Solution() res = ob.dijkstra(V,adj,S) for i in res: print(i,end=" ") print() # } Driver Code Ends
测试用例
样例输入
9 14 0 1 4 0 7 8 1 7 11 1 2 8 7 6 1 7 8 7 2 8 2 8 6 6 2 5 4 2 3 7 6 5 2 3 5 14 3 4 9 5 4 10 0
预期输出
0 4 12 19 21 11 9 8 14
实际输出
0 4 12 19 26 16 18 8 14
错误原因分析
代码存在三个核心逻辑错误:
- 优先队列存储值错误:
q.put([i[1],i[0]])这里插入队列的是单条边的权重i[1],而不是从起点到当前节点的总距离d,导致优先队列无法按照最短路径优先级弹出节点,处理顺序完全错误。 - 未过滤已处理节点的重复条目:Dijkstra算法中同一个节点可能对应多个不同路径长度的条目存在于优先队列中,当弹出节点时如果该节点已经被处理过(已确认最短距离),应该直接跳过后续处理,你的代码没有做这个判断。
- 入队条件错误:你判断只有节点不在
visited中才加入队列,但是即使节点已经被标记为已访问,只要找到了更短的路径,也需要将新的路径长度加入优先队列,否则更优路径会被丢弃。
修正后代码
from queue import PriorityQueue class Solution: #Function to find the shortest distance of all the vertices #from the source vertex S. def dijkstra(self, V, adj, S): q=PriorityQueue() # 初始距离设为无穷大,避免特殊值判断逻辑出错 distance=[float('inf')]*V distance[S]=0 visited=set() q.put([0, S]) while not q.empty(): current_dist, s = q.get() # 已处理过的节点直接跳过 if s in visited: continue visited.add(s) for neighbor, weight in adj[s]: d = current_dist + weight if d < distance[neighbor]: distance[neighbor] = d # 只要找到更短路径就加入队列,无需判断是否访问过 q.put([d, neighbor]) # 不可达节点返回-1适配题目要求 return [x if x != float('inf') else -1 for x in distance]
修正后代码运行样例输入可得到符合预期的输出结果。
内容的提问来源于stack exchange,提问作者Abhishek Jaiswal
相关产品推荐
相关产品推荐

