迪杰斯特拉算法 Python & C++ (例子)

⚡ 智能摘要

Dijkstra's Algorithm computes the shortest path from a single source vertex to every other vertex in a weighted graph with non-negative edges. This greedy method underpins Google 地图路由、OSPF IP 路由以及无数网络最短路径用例。

  • 🎯 核心理念: Dijkstra's Algorithm greedily expands the closest unvisited vertex, updating neighbor distances until every reachable node holds its true shortest cost from the source.
  • 🔄 与 BFS 和 DFS 相比: BFS 和 DFS 寻找不考虑边权重的任何路径,而 Dijkstra 则最小化带权重边的总成本。
  • 🧭 分步示例: 一个经过处理的 7 顶点加权图显示了距离是如何迭代更新的,以及路径 1-2-6-7 如何以 7 的成本获胜。
  • 💻 语言覆盖范围: 以上皆是 C++ 和 Python 实现演示了具有最小距离选择函数的邻接矩阵版本。
  • ⚠️ 局限性: Dijkstra 算法在负边权重图上失效,因为已确定的节点永远不会被重新考虑;对于具有负边的图,请使用 Bellman-Ford 算法。
  • 📊 复杂: 朴素数组版本在 O(V²) 时间和空间中运行;对于稀疏图,优先级队列可将时间降低到 O(E log V)。

迪杰斯特拉最短路径算法

什么是最短路径或最短距离?

从源顶点到目标顶点的路径,如果其成本最低,则称为最短路径或最短距离。在图论中,从源顶点到目标顶点可能有多条路径。在这些路径中,如果存在一条成本最低的路径,我们就称其为最短路径。

Here "cost" means the number of nodes in the route or the summation of costs on each edge. A path can have one or multiple edges. The connection between two vertices is called an "edge". There are various types of shortest path algorithms, such as Dijkstra's Algorithm and the Bellman-Ford Algorithm.

Here, we discuss Dijkstra's Algorithm. Let us look at the following weighted graph:

无向加权图

无向加权图

  • The term "weighted" means the cost of moving from one node to another. For example, moving from node 1 to node 2, the cost or weight is 1.
  • 节点 1 和节点 2 之间的路径称为边。
  • "Undirected" means you can move from one node to another and back to the previous node. So, if we try to find all the routes from node 1 to node 7, they will be:
路线或路径Cost
1-2-6-7(1+3+3)=7
1-2-3-7(1+9+1)=11
1-3-7(7 + 1)= 8
1-4-5-7(6+2+5)=13

在这四条路线中,我们可以看到第一条路线的成本为 7。因此,就成本而言,它是最短的路径。

最短的路径

最短的路径

Dijkstra 算法的工作原理

Dijkstra's Algorithm can find the shortest distance in both directed and undirected weighted graphs. This algorithm is greedy because it always chooses the shortest or closest node from the origin. The term "greedy" means that among a set of outcomes or results, the algorithm will choose the best of them.

Here, we are trying to find the shortest paths among all other routes. So, Dijkstra's Algorithm finds all the shortest paths from a single source node. As a result, it behaves like a 贪心算法.

In the "example" section below, you will see the step-by-step approach. It works as follows:

步骤1) 将起始节点初始化为成本 0,其余节点初始化为成本无穷大。
步骤2) 维护一个数组或列表以保存 track 个已访问节点。
步骤3) 将节点成本更新为最小成本。这可以通过比较当前成本和路径成本来实现(示例部分对此进行了演示)。
步骤4) 重复步骤 3,直到访问所有节点。

完成所有这些步骤后,我们将找到从源到目的地成本最低的路径。

Dijkstra 与 BFS、DFS 之间的区别

Dijkstra 算法与 BFS 和 DFS 的主要区别在于,Dijkstra 算法是最短路径查找算法,而 BFS 和 DFS 是通用路径查找算法。通常情况下,BFS 和 DFS 在查找路径时不考虑边的成本,因此这些算法不能保证找到最短路径。

二维网格演示广度优先搜索的工作原理

二维网格演示 BFS

阿尔戈斯凯奇,展示 BFS 演示

This demonstration indicates that BFS only finds the path. However, it does not care about the path's weight. BFS (广度优先搜索) 假设从一个节点到另一个节点的旅行仅花费 1。

让我们来看一个示例图:

二维网格演示示例图

在这里,BFS 算法在第二层找到了一条路径。BFS 算法按层顺序遍历图。因此,它的遍历路径如下:

步骤1) Start from node "1" and visit all the adjacent nodes 2, 3, 4.

步骤2) 将节点 2、3、4 标记为 1 级,并访问它们的相邻节点。程序将继续探索所有相邻节点,直到到达目标节点。

从DFS的角度来说,它将遍历从1到7的路径,如下所示:

  • 1→2→3→7(原始成本10,DFS成本3)
  • 1→2→6→7(原始成本7,DFS成本3)
  • 1→3→7 (原始成本8,DFS成本2)
  • 1→4→5→7(原始成本13,DFS成本3)

如我们所见,DFS 使用边的数量来计算路径成本。DFS 的工作原理如下:

  • DFS 可以找到从源(起始顶点)到目的地的路径。
  • 它不能保证从源节点到目的地发现的路径是否是最短路径。

However, in terms of Dijkstra's Algorithm, it chooses edges based on their cost. As a greedy algorithm, it will pick the minimum cost paths.

Dijkstra 算法的示例

Dijkstra's Algorithm uses the cost or weight to calculate the total cost of the path.

迪杰斯特拉算法示例

The target of Dijkstra's Algorithm is to minimize this total cost or weight. In the example shown above, we find the best paths from node 1 to node 7, then calculate all the costs.

In Dijkstra's Algorithm, it will find the shortest paths by calculating weights. It will not search for all possible paths. Let us demonstrate Dijkstra's Algorithm with an example. For example, you have been asked to find the shortest path from node 1 to 7.

对于此过程,步骤如下:

步骤1) 将起始节点成本初始化为 0。 "Inf" 对于其余节点而言,这意味着源节点和该节点之间不存在路径,或者该路径尚未被访问过。

Dijkstra 算法初始化

步骤2) 选择节点 1 后,将其标记为已访问。然后更新节点 1 的所有相邻节点。节点 2、3、4 是节点 1 的相邻节点。

在更新成本时,我们需要遵循以下步骤:

Dijkstra 算法更新程序

We can update each node's cost using the above formula. For example, we were at node 1, and we needed to update the cost of its adjacent nodes 2, 3, 4. After updating, the costs will look like this:

Dijkstra 算法在第一次更新后

步骤3) For node "2", neighbors are 6 and 3. We are updating the cost at "6" by comparing infinity (current value) with the cost of node 2 + path cost from 2 to 6. Simply put, node "6" will have the cost of 1+3 or 4.

Dijkstra 算法更新节点 6

节点 3 是节点 2 的邻居。但是,我们在上一步中计算了它的成本,即 7。现在,如果我们的路径是 1-2-3,则节点 3 的成本将为 10。路径 1-2-3 将花费 10,而 1 到 3 将花费 7。

步骤4) 对于节点 3,其相邻节点为 7。因此,将节点 7 的当前值与路径成本 (7+1) 或 8 进行比较,我们将更新节点 7 的成本,即 8。所以,我们找到了一条从节点 1 到节点 7 的路径,即 1→3→7,成本为 8。

步骤5) For node 4, we will update its adjacent node cost accordingly. So, node "5" will have an updated cost of 8. After step 4 and 5, it will look like this:

迪杰斯特拉算法在第 4 步之后 5

Now, the path 1-3-7 has the cost of 8 (previously). Node "7" was not marked visited because we can reach node "7" from node "6". The path "1-2-6" had a cost of 4. So the path 1-2-6-7 will have the cost of 7.

As 7 < 8, the shortest path from source vertex "1" to destination vertex "7" will be 1-2-6-7, and the cost is 7. Previously it was 1-3-7, and the cost was 8. So, the final graph will look like this:

Dijkstra 算法最终图

用黑线标记的边是我们从 1 到 7 的最短路径,它将花费我们 7。

昵称 Code 迪杰斯特拉算法

Here is the pseudo-code for Dijkstra's Algorithm:

Dijkstra(G, S):
  for each vertex V in G
    distance[V] <- Infinity
    previous[V] <- NULL
    if V does not equal S, then,
      (priority queue) Q.push(V)
  distance[S] = 0
  While Q is not empty
    U <- Extract the MIN from Q
    For each unvisited adjacent V of U
      TotalDistance <- distance[U] + edge_cost(U, V)
      if TotalDistance is less than distance[V], then
        distance[V] <- TotalDistance
        previous[V] <- U
  return distance, previous

C++ Dijkstra算法的实现

To implement Dijkstra's algorithm using C++以下是代码:

#include <bits/stdc++.h>
using namespace std;
#define size 7
int minimumDistance(int distance[], bool visited[]) {
  int min = INT_MAX;
  int min_index = INT_MAX;
  for (int i = 0; i < size; i++) {
    if (!visited[i] && distance[i] <= min) {
      min = distance[i];
      min_index = i;
    }
  }
  return min_index;
}
void printParentPath(int parent[], int i) {
  if (parent[i] == -1) {
    return;
  }
  printParentPath(parent, parent[i]);
  cout << i + 1 << " ";
}
void dijkstra(int graph[size][size], int source) {
  int distance[size];
  bool visited[size];
  int parent[size];
  for (int i = 0; i < size; i++) {
    parent[0] = -1;
    distance[i] = INT_MAX;
    visited[i] = false;
  }
  distance[source] = 0;
  for (int i = 0; i < size - 1; i++) {
    int U = minimumDistance(distance, visited);
    visited[U] = true;
    for (int j = 0; j < size; j++) {
      int curr_distance = distance[U] + graph[U][j];
      if (!visited[j] && graph[U][j] &&
          curr_distance < distance[j]) {
        parent[j] = U;
        distance[j] = curr_distance;
      }
    }
  }
  cout << "Vertex\t\tDistance\tPath" << endl;
  for (int i = 1; i < size; i++) {
    cout << source + 1 << "->" << i + 1 << "\t\t" << distance[i] << "\t\t"
         << source + 1 << " ";
    printParentPath(parent, i);
    cout << endl;
  }
}
int main() {
  int graph[size][size] = {{0, 1, 7, 6, 0, 0, 0}, {1, 0, 9, 0, 0, 3, 0},
                           {7, 9, 0, 0, 0, 0, 1}, {6, 0, 0, 0, 2, 0, 0},
                           {0, 0, 0, 2, 0, 0, 0}, {0, 3, 0, 0, 0, 0, 3},
                           {0, 0, 0, 0, 5, 3, 0}};
  dijkstra(graph, 0);
}

输出:

Vertex     Distance        Path

1->2           1             1 2
1->3           7             1 3
1->4           6             1 4
1->5           8             1 4 5
1->6           4             1 2 6
1->7           7             1 2 6 7

Python Dijkstra算法的实现

To implement Dijkstra's algorithm using Python以下是代码:

num_of_vertex = 7
def minimumDistance(distance, visited):
    _min = 1e11
    min_index = 1e11
    for i in range(num_of_vertex):
        if not visited[i] and distance[i] <= _min:
            _min = distance[i]
            min_index = i
    return min_index

def printParentNode(parent, i):
    if parent[i] == -1:
        return
    printParentNode(parent, parent[i])
    print("{} ".format(i + 1), end="")

def dijkstra(graph, src):
    distance = list()
    visited = list()
    parent = list()
    for i in range(num_of_vertex):
        parent.append(-1)
        distance.append(1e11)
        visited.append(False)
    distance[src] = 0
    for i in range(num_of_vertex - 1):
        U = minimumDistance(distance, visited)
        visited[U] = True
        for j in range(num_of_vertex):
            curr_distance = distance[U] + graph[U][j]
            if not visited[j] and graph[U][j] and curr_distance < distance[j]:
                parent[j] = U
                distance[j] = curr_distance
    print("Vertex\t\tDistance\tPath")
    for i in range(num_of_vertex):
        print("{}->{}\t\t{}\t\t{} ".format(src + 1, i + 1, distance[i], src + 1), end="")
        printParentNode(parent, i)
        print("")

graph = [
    [0, 1, 7, 6, 0, 0, 0],
    [1, 0, 9, 0, 0, 3, 0],
    [7, 9, 0, 0, 0, 0, 1],
    [6, 0, 0, 0, 2, 0, 0],
    [0, 0, 0, 2, 0, 0, 0],
    [0, 3, 0, 0, 0, 0, 3],
    [0, 0, 0, 0, 5, 3, 0]
]
dijkstra(graph, 0)

输出:

Vertex     Distance        Path

1->1           0              1
1->2           1              1 2
1->3           7              1 3
1->4           6              1 4
1->5           8              1 4 5
1->6           4              1 2 6
1->7           7              1 2 6 7

我们可以看到,该算法计算的是源节点到目标节点的最短距离。

Dijkstra 算法的应用

Dijkstra's Algorithm has a large set of uses. Among those, it is widely used in the field of networking. Here are some real-life uses of Dijkstra's Algorithm:

迪杰斯特拉 Google 地图功能: 从上面的代码片段输出可以看出,该算法是寻找最短路径的核心。

Dijkstra 算法的应用 Google 地图

Google 它不使用简单的Dijkstra算法,而是使用改进版本。当您选择目的地时,它会显示多条路径。 Google Maps. Among these paths, some are sorted out for the user. These paths are selected based on "time". So, "time" is an edge cost for the shortest path.

Dijkstra 在 IP 路由中的应用: IP路由 IP路由是网络术语,它描述了数据包如何通过不同的路径发送到接收方。这些路径包括路由器、服务器和其他设备。在IP路由中,存在不同类型的协议。

These protocols help the router find the shortest paths to send the data. One of the protocol names is "OSPF (Open Shortest Path First)". OSPF uses Dijkstra's algorithm. The router maintains a table of routes. Each router shares its table with neighbor routers. After receiving the updated table, they must calculate all the paths again. At that time, the router uses Dijkstra's Algorithm.

Dijkstra 算法的局限性

Dijkstra's algorithm cannot guarantee the shortest path in a graph with negative edges. Dijkstra's algorithm follows these principles:

  • 从一个节点到另一个节点将采用一条最短路径。
  • 两个节点之间的最短路径一旦选定,就不会再次计算。

这里,请注意两个具有负边缘的例子。

Dijkstra算法的局限性在于负边

左图中, 图上有三个顶点。Dijkstra算法将按如下方式应用于该图:

步骤1) Starting vertex "1" will be initialized to zero. The other nodes will have infinity.

Dijkstra算法的局限性(步骤1)

步骤2) Mark node "1" as visited and include it in the shortest path.

步骤3) The distance of the source node 1 to nodes "2" and "3" is set to infinity, as the shortest path is yet to be calculated. So, any path that costs less than infinity will be added to the shortest path (greedy approach).

步骤4) Updating the distance from source vertex "1" to "2". The current weight will be 5 (5 < infinity). Similarly, update the distance from node "1" to "3" with the weight of 3.

Dijkstra算法的局限性(步骤4)

步骤5) Now if we check the shortest distances from node "1", we find that 5 is the shortest distance for edge 1→2. So, node "2" will be marked as visited. Similarly, node "3" will also be marked as visited as the shortest distance is 3.

However, if we observe, there is a path 1-3-2 that will cost only 2. But Dijkstra shows that from node "1" to node "2", the shortest distance is 5. So, Dijkstra failed to calculate the shortest distance correctly. The reason is that Dijkstra is a greedy algorithm. So, once a node is marked visited, it will not be reconsidered, although there might be a shorter path available. This issue only occurs when the edges have negative costs or negative weight edges.

Dijkstra fails to calculate the shortest path between two nodes in this scenario. As a result, this algorithm has some drawbacks. To solve this negative edge problem, another algorithm called the "Bellman-Ford Algorithm" is used. That algorithm can work with negative edges.

Dijkstra 算法的复杂性

The implementation above used two "for" loops. These loops run for the number of vertices. So, the time complexity is O(V²). Here, the term "O" is a notation that gives an assumption for the Dijkstra algorithm.

We can store the graph using a "priority queue". A priority queue is a binary heap data structure. It will be more efficient than a 2D matrix. An edge with a minimum cost will have a high priority. Then the time complexity will be O(E log V)。其中,E为边数,V为顶点数。

空间复杂度为 O(V²),因为我们使用邻接矩阵(二维阵列)。可以使用邻接表或队列数据结构来优化空间复杂度。

常见问题

机器人、自动驾驶车辆和游戏NPC中的AI路径规划代理使用Dijkstra算法在加权图上寻找成本最低的路径。强化学习环境也依赖该算法来计算奖励共享的最优参考路径。ping 和评估。

是的。像 GitHub Copilot 和 GPT 这样的 AI 编码助手可以生成 Dijkstra 算法。 Python, C++ 或 Java包括使用堆的优先级队列变体。它们还可以打印实际的最短路径,或将代码适配到以邻接表形式存储的图。

Using a simple array to find the minimum node, Dijkstra's Algorithm runs in O(V²) time. With a binary heap priority queue it drops to O((V + E) log V), and with a Fibonacci heap it reaches O(E + V log V), best for sparse graphs.

Dijkstra算法一旦选定当前最短距离,就会立即确定一个顶点。之后可能出现一条更短的路径,但由于该顶点已被确定,算法不会再次访问它,因此会报告错误的最短距离。

当所有边的权重均为非负数时,选择 Dijkstra 算法,因为它速度更快,时间复杂度为 O((V+E) log V)。当边的权重可能为负数或需要检测负权重环时,选择 Bellman-Ford 算法;其运行时间为 O(V·E),这是两者之间的权衡。

Google Maps 使用了 Dijkstra 算法的变体和后续算法,包括 A* 和 Con 算法。trac交通层级结构,针对道路网络和实时交通情况进行了优化。以最小累积成本进行贪婪扩张的基本思想仍然是迪杰斯特拉的核心贡献。

A* 算法在 Dijkstra 算法的基础上,增加了一个目标距离的启发式估计,当有较好的启发式估计时,A* 算法会扩展更少的节点。Dijkstra 算法会向所有方向搜索,而 A* 算法则将搜索重心放在目标上,因此在实践中速度更快。

除了地图之外,Dijkstra 算法还为互联网上的 OSPF 和 IS-IS 路由协议、网络拓扑优化、电话呼叫路由、机器人运动规划、社交网络最短连接查询以及航空公司航班成本最小化提供支持。

总结一下这篇文章: