编程学习与职业发展:从算法到实践
一、图算法与数据结构
(一)Dijkstra 算法
Dijkstra 算法用于寻找图中从一个顶点到其他所有顶点的最短路径。以下是其核心代码及原理:
if current_distance > distances[current_vertex]:
continue
for neighbor, weight in graph[current_vertex].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
原理说明:
1. 当当前距离 current_distance 大于已记录的该顶点的最短距离 distances[current_vertex] 时,跳过该路径,使用 continue 关键字回到 while 循环顶部检查其他顶点。
2. 若当前距离不大于已记录的最短距离,则遍历当前顶点的所有相邻顶点。
3. 计算每个相邻顶点到起始顶点的距离,即 current_distance 加上相邻顶点与当前顶点之间的权重
超级会员免费看
订阅专栏 解锁全文
13万+

被折叠的 条评论
为什么被折叠?



