迪杰斯特拉算法

迪杰斯特拉算法(Dijkstra)是由荷兰计算机科学家狄克斯特拉于1959 年提出的,因此又叫狄克斯特拉算法。是从一个顶点到其余各顶点的最短路径算法,解决的是有权图中最短路径问题。迪杰斯特拉算法主要特点是以起始点为中心向外层层扩展,直到扩展到终点为止。

该算法的目标:带权图求最短路径

对于带权图需要借助优先队列来实现。

python提供了优先队列这种结构,参考如下:

import heapq
#PriorityQueue
pqueue = []  
heapq.heappush(pqueue, (1, 'A'))
heapq.heappush(pqueue, (7, 'B'))
heapq.heappush(pqueue, (3, 'C'))
heapq.heappush(pqueue, (6, 'D'))
heapq.heappush(pqueue, (2, 'E'))
while len(pqueue) > 0:
	print(heapq.heappop(pqueue))

在这里插入图片描述

在这里插入图片描述

代码实现:

import heapq
import math
graph = {
	"A": {"B": 5, "C": 1},
	"B": {"A": 5, "C": 2, "D": 1},
	"C": {"A": 1, "B": 2, "D": 4, "E": 8},
	"D": {"B": 1, "C": 4, "E": 3, "F": 6},
	"E": {"C": 8, "D": 3},
	"F": {"D": 6}
}
def init_distance(graph, s):
	distance = {s: 0}
	for vertex in graph:
		if vertex != s:
			distance[vertex]=math.inf
	return distance
# s代表开始的结点
def dijkstra(graph, s):
	pqueue = []
	heapq.heappush(pqueue,(0, s))
	seen = set()  #定义一个集合
	parent = {s: None}
	distance = {s: 0}
	distance = init_distance(graph, s)
	while len(pqueue)>0:
		pair = heapq.heappop(pqueue)
		dist = pair[0]
		vertex = pair[1]
		seen.add(vertex)
		nodes = graph[vertex].keys()
		for w in nodes:
			if w not in seen:
				if (dist + graph[vertex][w])< distance[w]:
					heapq.heappush(pqueue, (dist + graph[vertex][w], w))
					parent[w] = vertex
					distance[w] = dist + graph[vertex][w]
		# print(vertex)
	return parent, distance
# parent = BFS(graph, 'E')
# print(parent)
# v = 'B'
# while v!= None:
# 	print(v)
# 	v = parent[v]
parent, distance = dijkstra(graph, 'A')
print(parent, distance)

整理自:https://www.bilibili.com/video/av25829980/?spm_id_from=333.788.videocard.1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

. . . . .

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值