Dijkstra算法是一种用于计算一个节点到其他所有节点的最短路径的算法,它的基本思路是:
将所有节点的距离初始化为无穷大,除了起点,将其初始化为0。
建立一个小根堆来存储所有节点,并按照距离进行排序。
取出堆中最小的节点,标记为已经访问过。
对于该节点的所有相邻节点,检查是否有更短的路径,如果有,则更新它们的距离。
重复步骤3和4,直到所有节点都被访问过。
下面是一个使用Dijkstra算法的Python代码的例子:
```
定义图的边
class Edge: def init(self, destination, weight): self.destination = destination self.weight = weight
定义图的节点
class Node: def init(self, name): self.name = name self.visited = False self.predecessor = None self.adjacencies_list = [] self.min_distance = float("inf") # 将所有节点的距离初始化为无穷大
定义图
class Graph: def init(self): self.nodes_list = []
def add_edge(self, source, destination, weight):
# 建立边
edge = Edge(destination, weight)
# 将边添加到节点的邻接表中
source.adjacencies_list.append(edge)
定义优先队列
class PriorityQueue: def init(self): self.nodes_list = []
def push(