Dijkstra's algorithm-python实现


def find_lowest_cost_node(costs):
	lowest_cost = float("inf")
	lowest_cost_node = None
	for node in costs:
		cost = costs[node]
		if cost < lowest_cost and node not in processed:
			lowest_cost = cost
			lowest_cost_node = node
	return lowest_cost_node

def dijkstra(costs):
	#在未处理的节点中找出开销最小的节点
	node = find_lowest_cost_node(costs)
	#这个while循环在所有节点都被处理过后结束
	while node is not None:
		cost = costs[node]
		neighbors = graph[node]
		#遍历当前节点的所有邻居
		for n in neighbors.keys():
			new_cost = cost + neighbors[n]
			#如果经当前节点前往该邻居更近
			if costs[n] > new_cost:
				#就更新邻居的开销
				costs[n] = new_cost
				#同时将该邻居的父节点设置为当前节点
				parents[n] = node
		#将当前节点标记为处理过
		processed.append(node)
		#炸出接下来要处理的节点,并循环
		node = find_lowest_cost_node(costs)


graph = {}
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2

# print(graph.values())
# print(graph.keys())
# print(graph.items())
# print(graph)
# print()
# print(graph["start"].values())
# print(graph["start"].keys())
# print(graph["start"].items())
# print(graph["start"])
# print(graph["start"]["a"])

graph["a"] = {}
graph["a"]["fin"] = 1

graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["fin"] = 5

graph["fin"] = {}
print("{}:{}".format("initial graph",graph))

infinity = float("inf")

#创建开销表
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity
print("{}:{}".format("initial costs",costs))

#创建存储父节点的散列表
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = None
print("{}:{}".format("initial parents",parents))

#记录处理过的节点
processed = []
dijkstra(costs)
print()
print("{}:{}".format("finial costs",costs))
print("{}:{}".format("finial parents",parents))

运行结果:

initial graph:{'start': {'a': 6, 'b': 2}, 'a': {'fin': 1}, 'b': {'a': 3, 'fin': 5}, 'fin': {}}
initial costs:{'a': 6, 'b': 2, 'fin': inf}
initial parents:{'a': 'start', 'b': 'start', 'fin': None}

finial costs:{'a': 5, 'b': 2, 'fin': 6}
finial parents:{'a': 'b', 'b': 'start', 'fin': 'a'}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值