使用Dijkstra算法构建基于Raspberry Pi Pico的路线查找器
20世纪50年代,荷兰计算机科学家艾兹格·迪杰斯特拉(Edsger Dijkstra)开发了一种极为重要的路径查找算法,70年后的今天,它仍然属于计算机科学课程的核心内容。在本文中,我们将探讨Dijkstra算法的作用、工作原理,并了解其应用场景。过程中,我们会复习一些Python编程技巧,寻找宝藏,同时使用树莓派 Pico.
如何让您的导航系统找到回家的路?网络如何决定数据包的传输路径?机器人如何绕过障碍物?所有这些问题的答案都是通过创建一个由数据节点连接而成的图,然后利用类似Dijkstra算法的方法从图中生成路由信息。
Dijkstra算法
图1显示了Pico路线查找器。它包含英国各地位置的地图信息,可以告诉你这些地点之间的距离和路线。让我们看看Dijkstra算法是如何让它工作的,从该算法的起源开始。

故事是这样的:迪杰斯特拉在阿姆斯特丹喝咖啡时思考着导航问题。他心中还想着要写点什么来展示他正在使用的新型计算机。经过几分钟的思考,他提出了自己的算法,其核心可归结为三条规则:
- 记录到达各处的成本
- 探索时始终优先选择成本最低的路径
- 记录已访问过的位置
让我们看看如何运用这些规则来寻找通往宝藏的最便宜路线。假设我们正在参观一座城堡,主人告诉我们:
“我希望你规划一条从大厅到我的藏宝室的路径,那里放着一堆金币。你可以拿走藏宝室里的所有金币,但需扣除到达那里的成本。你路径上的每扇门都有成本。你可以随意在城堡内游荡,但当你完成之后,可以在藏宝室与我见面,告诉我你设计的路径,我将给你相应的奖励。”
门上的分数
我们环顾大厅,看到三扇标有标签的门,如图2所示。标签上写着“厨房:成本5”,“图书馆:成本2”,“藏宝室:成本100”。我们可以直接前往藏宝室,这需要花费100枚金币。或者,我们可以尝试寻找更便宜的路线。幸运的是,我们是熟悉Dijkstra算法的计算机科学家,于是打开笔记本,画出一张表格。每扇门都告诉我们一个新房间以及从该房间到达所需的成本。我们将这些信息填入表格,从我们所在的大厅开始。

图3显示了我们的第一张表。它描述了我们所知的房间,是否已访问过,从大厅到达每个房间的费用,以及返回旅程起点的路线。迪杰斯特拉算法指出,我们现在应找到未访问过的最低费用房间,前往该房间,并更新我们的表格。因此,我们前往图书馆。

要黄金,愿远行
门在图4告诉我们从图书馆到厨房的费用是2,到铠甲室的费用是4。它们还告诉我们,回到大厅的费用是2,但我们早已从大厅的门中得知这一点。我们使用这些数字来更新表格。让我们先来看铠甲室:从图书馆到铠甲室需要花费4,而从大厅到图书馆需要花费2。因此,从大厅到铠甲室的总费用为6。我们在表格中加入铠甲室,并注明从铠甲室返回大厅的路线首先经过图书馆,然后继续前往大厅。

现在我们可以更新表格以节省一些金币。迪杰斯特拉算法告诉我们需要跟踪旅程成本。如果我们发现一个新的成本低于表格中的值,就需要更新表格。从大厅到图书馆花费2,再从图书馆到厨房花费2,总共为4。最初,直接从大厅到厨房的费用被记录为5(即大厅门上的费用)。但如果我们通过图书馆从大厅前往厨房,就能省下一枚金币。我们用这一新信息更新表格。
图5显示了更新后的表格,过时的信息已被划掉。我们的下一个目的地将是未访问过的最低费用房间,即厨房。我们进入厨房并重复此过程,直到最终到达宝库。

最终结算
图6显示了我们旅途中创建的表格。它告诉我们所需的一切信息。从大厅到宝库的最便宜路线需花费18枚金币。我们利用表格中的“返回路线”列,找出从宝库返回大厅的路径。返回大厅的第一步是前往卧室。然后查看卧室的“返回路线”值,找到下一步,如此类推。完整的返回路线是:卧室 > 餐厅 > 厨房 > 图书馆 > 大厅。你可以在图6中自行验证。我们反过来排列这条路径,即可得到从大厅到宝库的路线。

图7展示了我们在旅途中构建的城堡地图。这并不完整,仅显示了我们所知的房间。如果你想证明该算法有效,可以自行完成路径查找过程,以构建如图6.

使用迪杰斯特拉算法获胜
当你注意到算法如何忽略不在最佳路径上的地点时,它的巧妙之处便显现出来。我们从未访问过马厩,因为通往那里的路线比我们先检查的其他更便宜的路线要贵。在戴克斯特拉提出他的定理时,计算机的主存非常有限。他的路径查找演示仅限于64个位置,因为他的程序使用六个数据位来存储每个位置编号。戴克斯特拉最初取得巨大成功的关键之一,就是将所有位置信息和代码都塞进了极小的内存空间中。
编写戴克斯特拉算法
我们不必使用笔记本记录开销,而是可以在Python中创建自己的开销跟踪程序。首先我们需要创建一个用于存储每个房间的数据结构:
class NodeRouteData:
def __init__(self, name, cost, route_back):
self.name = name
self.visited = False
self.cost = cost
self.route_back = route_back
上面的代码创建了一个名为NodeRouteData. This stores all the information about a location in the castle. We’re calling each location a ‘node’ because we might want to use this program to navigate things other than rooms in a castle. The class contains fields which map directly onto what we put in our notebook. When we create an instance of the class, we set the name, cost, and the route back from this node. Now let’s ask the user where they are starting from and where they are going:
start_name = input("起始点名称: ")
end_name = input("终点名称: ")
上述语句读取起始点和终点的名称,并将其存储在名为start_name andend_name. Next, we need to make a node to represent the start location. We don’t need to make a node for the end location; we use the value in end_name to detect when we have found a route to it.
start_node = NodeRouteData(start_name, 0, None)
上述语句创建了一个NodeRouteData called start_node, with the name set to start_name. The first argument to the constructor of NodeRouteData is the name of the node. The second argument is the cost of going there. For the start node this is 0, because it is where we start. The third argument is the route back (i.e. the place we go to on the way back to the start). Since this is the start, we have no route back, so this value is set to None. Now we need to put the start node in the table. We can use a Python dictionary to hold the table, and the name of a node will be used as the key to find that node in the dictionary.
nodes = {}
nodes[start_name] = start_node
上述语句创建了一个空字典,名为nodes and add the start room to it. You add an item to a dictionary by specifying a key (the thing that will be used to find the item), as shown above. Now we can start checking the doors in nodes and updating costs. We use a variable called current_node to refer to the node we are working on. At the start of our exploration, the current node will be the start node:
current_node = start_node
上述语句创建了current_node and sets it to start_node. Now let’s kick off our loop:
while current_node.name != end_name:
上述语句启动了一个while loop that will cause the program to inspect nodes until it reaches one with the same name as the end of our route. Because the algorithm always chooses routes with the lowest cost, we will have found our cheapest route when the two names match. Inside the loop, we will do exactly what we did when we were physically exploring the castle. We look for doors and use the information on them to update our table. There might be more than one door, so we need to create a ‘door reading’ loop:
while True:
name = input("房间名称(输入空值结束): ")
if name == "":
break
上述语句创建了一个循环,首先从一扇门处获取房间名称。如果名称为空字符串,说明该位置已无更多门,因此代码使用break to leave the door-reading loop. If the user has entered a name, the program asks for the cost of the route.
cost_string = input("Cost :")
cost = int(cost_string)
上述语句设置变量cost_string to the string that the user types in and then convert this string into an integer stored in the variable cost. Now we can use this new cost value to update our table. The first thing we do is work out the cost of getting to the room on the door from the start location. This will be the cost of getting to this room, plus the cost on the door:
total_cost = cost + current_node.cost
现在我们有了一个节点的名称以及到达该节点的总成本。如果这是一个我们之前没见过的节点,就需要将其添加到 nodes 中。让我们来实现这一点。
if name not in nodes:
nodes[name] = NodeRouteData(name,
total_cost,
current_node)
上述代码检查了nodes dictionary to see if it contains an entry for the node with the name that was typed in. If the answer is no, the program adds a new node to the dictionary. We set the route back and the cost values for the new node.
如果该节点已在字典中,我们需要检查是否找到了一条更便宜的到达路径。我们可以通过添加一个else part to the condition we just wrote. This code will run if the dictionary contains a node with the name on the door.
else:
room = nodes[name]
if total_cost < room.cost:
room.cost = total_cost
room.route_back = current_node
这段代码从字典中获取对房间的引用,然后比较通过新发现的门到达该房间的成本与已存储的到达成本。如果新路线更便宜,我们就更新房间数据。这相当于在笔记本上划掉旧的成本和回溯路径并写下新的内容。
一旦知道了某个房间的所有门的信息,用户就会输入一个空的房间名称,此时房间循环结束。现在我们需要记录我们已经访问过这个房间,以免再次进入:
current_node.visited=True
现在我们已经更新了路由表,接下来需要决定去往何处。我们需要在表中找到下一个最便宜的路径,并前往该路径所指向的位置:
cheapest_node = None
for node in nodes.values():
if node.visited:
continue
if cheapest_node == None or node.cost < cheapest_node.cost:
cheapest_node = node
这段代码设置了cheapest_node to the node which has not been visited and has the lowest cost. Now we can switch to it:
print(f"下一个节点是 {cheapest_node.name}")
current_node = cheapest_node
这两条语句告诉用户下一步该去哪里,然后设置current_node to the cheapest one. Note that the next node might not be through one of the doors that have just been discovered. At some point the loop will stop, because the cheapest_node becomes the one with the end name and the while loop will exit. This is where we tell the user the cost of the route and describe it to them. Displaying the cost of the route is the simpler of the two:
print(f"成本:{current_node.cost}")
当current_node refers to the node with the name of the end_node. So we just print out the cost of getting to the current node. This will print a cost of 18 coins. Now we build a route by working through all the route_back values of nodes in the route:
route = []
while current_node != None:
route.append(current_node.name)
current_node = current_node.route_back
上面的代码使用一个循环来构建一个名为route. It starts at the end node and works back to the start. The start_node was created with a route_back value of None, so the loop will stop when it reaches the start. The loop adds the name of each node to the route list.
我们现在有了一个节点名称列表,但顺序是错误的。在打印之前,我们需要将其反转。
route.reverse()
print("路线:", " -> ".join(route))
这两行代码将路线反转,然后以“ -> ”分隔符打印出路线中的名称。这个非常棒的结果是:join method works on a string, takes the elements in a collection, and inserts the string between each item in the collection.
厅堂 -> 图书馆 -> 厨房 -> 餐厅 -> 卧室 -> 宝藏室
上述语句是成功运行的结果。本文的示例代码包含该算法的实现。如果你已经走到了这一步,可以深呼吸一下,为自己感到非常自豪。你现在知道如何实现迪杰斯特拉算法了。你对 Python 类、字典和引用也有了更深入的理解。
地图导航
我们可以修改城堡导航程序,以绘制英国的路线。首先,我们需要一个描述各个地点之间路线的图。在不同上下文中,“图”这个词有多种含义。最熟悉的可能是笛卡尔坐标图,它用于表示一个值相对于另一个值的变化(例如价格随时间变化)。而在路径规划中,我们使用的是节点图。它描述了地点(节点)以及它们之间的路径。以下是一个用 JSON 文件表示的例子。

代码在map_graph.json列表中显示了图的前半部分。它包含一个以城市名称为索引的城市字典。每个城市都有地理位置,以及与邻近城市相连的链接和成本(距离)列表。对城堡导航程序的修改版本使用此节点图,找出两个城市之间的最短路径。Pico 路线查找器使用相同的代码创建路线,然后在 LCD 面板上显示。
迪杰斯特拉算法永不过时
迪杰斯特拉算法通过按顺序找到所有最低成本路径,直到找到目标目的地为止。当从伦敦导航到赫尔时,它在找到通往赫尔的路径之前,先找到了通往特鲁罗(离伦敦和赫尔都很远)的路径。因此,现代导航系统不使用纯粹的迪杰斯特拉算法,而是会判断一条候选路径是朝向还是远离目的地,从而减少搜索范围。但在许多情况下,它仍然是创建路径的最佳方式,它将始终是计算机系统寻找路径的重要组成部分。
暂无评论
跳转到评论表单