当前位置:   article > 正文

5种语言实现 | 使用Dijkstra算法从起点到所有节点找到最短路径_dijkstra程序

dijkstra程序

编辑:东岸因为@一点人工一点智能

5种语言实现 | 使用Dijkstra算法从起点到所有节点找到最短路径C++\x5cJava\x5cPython\x5cC#\x5cJavascript,五种语言实现使用Dijkstra算法从起点到所有节点找到最短路径icon-default.png?t=N7T8https://mp.weixin.qq.com/s/6NAClr51zR_GLZGyKkr32A给定一个带权重的图和图中的一个起点,找到该点到图中所有其他节点的最短路径。

注意:给定的图中不包含任何负边。

示例:

Input: src = 0, the graph is shown below.

  1. Output: 0 4 12 19 21 11 9 8 14
  2. Explanation: The distance from 0 to 1 = 4.
  3. The minimum distance from 0 to 2 = 12. 0->1->2
  4. The minimum distance from 0 to 3 = 19. 0->1->2->3
  5. The minimum distance from 0 to 4 = 21. 0->7->6->5->4
  6. The minimum distance from 0 to 5 = 11. 0->7->6->5
  7. The minimum distance from 0 to 6 = 9. 0->7->6
  8. The minimum distance from 0 to 7 = 8. 0->7
  9. The minimum distance from 0 to 8 = 14. 0->1->2->8

01 使用邻接矩阵的Dijkstra算法

思路是以给定起点为根节点生成一个最短路径树(SPT)。维护一个包含两个集合的邻接矩阵,

· 一个集合包含在最短路径树中的节点,

· 另一个集合包含尚未包含在最短路径树中的节点。

算法的每个步骤中,找到一个在另一个集合中(尚未包含的集合)且距离起点最小的节点。

1.1 算法

* 创建一个集合sptSet(最短路径树集合),用于跟踪包含在最短路径树中的节点,即已计算和完成的距离起点的最小距离。初始时,此集合为空。

* 为输入图中的所有节点赋予一个距离值。将所有距离值初始化为无穷大。将起点的距离值设置为0,以便首先选择它。

当sptSet未包含所有节点时

· 选择一个不在sptSet中且具有最小距离值的节点u。

· 将u包含到sptSet中。

· 然后更新u的所有邻接节点的距离值。

        - 为了更新距离值,迭代遍历所有邻接节点。

        - 对于每个邻接节点v,如果u到v的距离值(从起点开始)加上边权重小于v的距离值,则更新v的距离值。

注意:我们使用一个布尔数组sptSet[]来表示包含在SPT中的节点集合。如果值sptSet[v]为true,则表示节点v包含在SPT中,否则不包含。数组dist[]用于存储所有节点的最短距离值。

1.2 Dijkstra算法的示例

为了理解Dijkstra算法,我们来看一个图,并找到从起点到所有节点的最短路径。

考虑下面的图和起点src = 0。

步骤1:

· 集合sptSet最初为空,节点的距离值分别是{0, INF, INF, INF, INF, INF, INF, INF},其中INF表示无穷大。

· 现在选择具有最小距离值的节点。选择节点0,并将其包含在sptSet中。因此,sptSet变为{0}。将0包含在sptSet中后,更新其相邻节点的距离值。

· 节点0的相邻节点是1和7。将1和7的距离值更新为4和8。

以下子图显示了节点及其距离值,只显示具有有限距离值的节点。包含在最短路径树中的节点以绿色显示。

步骤2:

· 选择具有最小距离值且尚未包含在SPT中(不在sptSet中)的节点。选择节点1并将其添加到sptSet中。

· 因此,sptSet现在变为{0, 1}。更新节点1的相邻节点的距离值。

· 节点2的距离值变为12。

步骤3:

· 选择具有最小距离值且尚未包含在SPT中(不在sptSet中)的节点。选择节点7。因此,sptSet现在变为{0, 1, 7}。

· 更新节点7的相邻节点的距离值。节点6和8的距离值变为有限值(分别为15和9)。

步骤4:

· 选择具有最小距离值且尚未包含在SPT中(不在sptSet中)的节点。选择节点6。因此,sptSet现在变为{0, 1, 7, 6}。

· 更新节点6的相邻节点的距离值。节点5和8的距离值被更新。

图片

我们重复上述步骤,直到sptSet包含了给定图的所有节点。最后,我们得到以下最短路径树(SPT)。

图片

02 代码实现

C++语言:

  1. // C++ Program to find Dijkstra's shortest path using
  2. // priority_queue in STL
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5. #define INF 0x3f3f3f3f
  6. // iPair ==> Integer Pair
  7. typedef pair<int, int> iPair;
  8. // This class represents a directed graph using
  9. // adjacency list representation
  10. class Graph {
  11. int V; // No. of vertices
  12. // In a weighted graph, we need to store vertex
  13. // and weight pair for every edge
  14. list<pair<int, int> >* adj;
  15. public:
  16. Graph(int V); // Constructor
  17. // function to add an edge to graph
  18. void addEdge(int u, int v, int w);
  19. // prints shortest path from s
  20. void shortestPath(int s);
  21. };
  22. // Allocates memory for adjacency list
  23. Graph::Graph(int V)
  24. {
  25. this->V = V;
  26. adj = new list<iPair>[V];
  27. }
  28. void Graph::addEdge(int u, int v, int w)
  29. {
  30. adj[u].push_back(make_pair(v, w));
  31. adj[v].push_back(make_pair(u, w));
  32. }
  33. // Prints shortest paths from src to all other vertices
  34. void Graph::shortestPath(int src)
  35. {
  36. // Create a priority queue to store vertices that
  37. // are being preprocessed. This is weird syntax in C++.
  38. // Refer below link for details of this syntax
  39. // https://www.geeksforgeeks.org/implement-min-heap-using-stl/
  40. priority_queue<iPair, vector<iPair>, greater<iPair> >
  41. pq;
  42. // Create a vector for distances and initialize all
  43. // distances as infinite (INF)
  44. vector<int> dist(V, INF);
  45. // Insert source itself in priority queue and initialize
  46. // its distance as 0.
  47. pq.push(make_pair(0, src));
  48. dist[src] = 0;
  49. /* Looping till priority queue becomes empty (or all
  50. distances are not finalized) */
  51. while (!pq.empty()) {
  52. // The first vertex in pair is the minimum distance
  53. // vertex, extract it from priority queue.
  54. // vertex label is stored in second of pair (it
  55. // has to be done this way to keep the vertices
  56. // sorted distance (distance must be first item
  57. // in pair)
  58. int u = pq.top().second;
  59. pq.pop();
  60. // 'i' is used to get all adjacent vertices of a
  61. // vertex
  62. list<pair<int, int> >::iterator i;
  63. for (i = adj[u].begin(); i != adj[u].end(); ++i) {
  64. // Get vertex label and weight of current
  65. // adjacent of u.
  66. int v = (*i).first;
  67. int weight = (*i).second;
  68. // If there is shorted path to v through u.
  69. if (dist[v] > dist[u] + weight) {
  70. // Updating distance of v
  71. dist[v] = dist[u] + weight;
  72. pq.push(make_pair(dist[v], v));
  73. }
  74. }
  75. }
  76. // Print shortest distances stored in dist[]
  77. printf("Vertex Distance from Source\n");
  78. for (int i = 0; i < V; ++i)
  79. printf("%d \t\t %d\n", i, dist[i]);
  80. }
  81. // Driver's code
  82. int main()
  83. {
  84. // create the graph given in above figure
  85. int V = 9;
  86. Graph g(V);
  87. // making above shown graph
  88. g.addEdge(0, 1, 4);
  89. g.addEdge(0, 7, 8);
  90. g.addEdge(1, 2, 8);
  91. g.addEdge(1, 7, 11);
  92. g.addEdge(2, 3, 7);
  93. g.addEdge(2, 8, 2);
  94. g.addEdge(2, 5, 4);
  95. g.addEdge(3, 4, 9);
  96. g.addEdge(3, 5, 14);
  97. g.addEdge(4, 5, 10);
  98. g.addEdge(5, 6, 2);
  99. g.addEdge(6, 7, 1);
  100. g.addEdge(6, 8, 6);
  101. g.addEdge(7, 8, 7);
  102. // Function call
  103. g.shortestPath(0);
  104. return 0;
  105. }

Java语言:

  1. import java.util.*;
  2. class Graph {
  3. private int V;
  4. private List<List<iPair>> adj;
  5. Graph(int V) {
  6. this.V = V;
  7. adj = new ArrayList<>();
  8. for (int i = 0; i < V; i++) {
  9. adj.add(new ArrayList<>());
  10. }
  11. }
  12. void addEdge(int u, int v, int w) {
  13. adj.get(u).add(new iPair(v, w));
  14. adj.get(v).add(new iPair(u, w));
  15. }
  16. void shortestPath(int src) {
  17. PriorityQueue<iPair> pq = new PriorityQueue<>(V, Comparator.comparingInt(o -> o.first));
  18. int[] dist = new int[V];
  19. Arrays.fill(dist, Integer.MAX_VALUE);
  20. pq.add(new iPair(0, src));
  21. dist[src] = 0;
  22. while (!pq.isEmpty()) {
  23. int u = pq.poll().second;
  24. for (iPair v : adj.get(u)) {
  25. if (dist[v.first] > dist[u] + v.second) {
  26. dist[v.first] = dist[u] + v.second;
  27. pq.add(new iPair(dist[v.first], v.first));
  28. }
  29. }
  30. }
  31. System.out.println("Vertex Distance from Source");
  32. for (int i = 0; i < V; i++) {
  33. System.out.println(i + "\t\t" + dist[i]);
  34. }
  35. }
  36. static class iPair {
  37. int first, second;
  38. iPair(int first, int second) {
  39. this.first = first;
  40. this.second = second;
  41. }
  42. }
  43. }
  44. public class Main {
  45. public static void main(String[] args) {
  46. int V = 9;
  47. Graph g = new Graph(V);
  48. g.addEdge(0, 1, 4);
  49. g.addEdge(0, 7, 8);
  50. g.addEdge(1, 2, 8);
  51. g.addEdge(1, 7, 11);
  52. g.addEdge(2, 3, 7);
  53. g.addEdge(2, 8, 2);
  54. g.addEdge(2, 5, 4);
  55. g.addEdge(3, 4, 9);
  56. g.addEdge(3, 5, 14);
  57. g.addEdge(4, 5, 10);
  58. g.addEdge(5, 6, 2);
  59. g.addEdge(6, 7, 1);
  60. g.addEdge(6, 8, 6);
  61. g.addEdge(7, 8, 7);
  62. g.shortestPath(0);
  63. }
  64. }

Python 3 语言:

  1. import heapq
  2. # iPair ==> Integer Pair
  3. iPair = tuple
  4. # This class represents a directed graph using
  5. # adjacency list representation
  6. class Graph:
  7. def __init__(self, V: int): # Constructor
  8. self.V = V
  9. self.adj = [[] for _ in range(V)]
  10. def addEdge(self, u: int, v: int, w: int):
  11. self.adj[u].append((v, w))
  12. self.adj[v].append((u, w))
  13. # Prints shortest paths from src to all other vertices
  14. def shortestPath(self, src: int):
  15. # Create a priority queue to store vertices that
  16. # are being preprocessed
  17. pq = []
  18. heapq.heappush(pq, (0, src))
  19. # Create a vector for distances and initialize all
  20. # distances as infinite (INF)
  21. dist = [float('inf')] * self.V
  22. dist[src] = 0
  23. while pq:
  24. # The first vertex in pair is the minimum distance
  25. # vertex, extract it from priority queue.
  26. # vertex label is stored in second of pair
  27. d, u = heapq.heappop(pq)
  28. # 'i' is used to get all adjacent vertices of a
  29. # vertex
  30. for v, weight in self.adj[u]:
  31. # If there is shorted path to v through u.
  32. if dist[v] > dist[u] + weight:
  33. # Updating distance of v
  34. dist[v] = dist[u] + weight
  35. heapq.heappush(pq, (dist[v], v))
  36. # Print shortest distances stored in dist[]
  37. for i in range(self.V):
  38. print(f"{i} \t\t {dist[i]}")
  39. # Driver's code
  40. if __name__ == "__main__":
  41. # create the graph given in above figure
  42. V = 9
  43. g = Graph(V)
  44. # making above shown graph
  45. g.addEdge(0, 1, 4)
  46. g.addEdge(0, 7, 8)
  47. g.addEdge(1, 2, 8)
  48. g.addEdge(1, 7, 11)
  49. g.addEdge(2, 3, 7)
  50. g.addEdge(2, 8, 2)
  51. g.addEdge(2, 5, 4)
  52. g.addEdge(3, 4, 9)
  53. g.addEdge(3, 5, 14)
  54. g.addEdge(4, 5, 10)
  55. g.addEdge(5, 6, 2)
  56. g.addEdge(6, 7, 1)
  57. g.addEdge(6, 8, 6)
  58. g.addEdge(7, 8, 7)
  59. g.shortestPath(0)

C#语言:

  1. using System;
  2. using System.Collections.Generic;
  3. // This class represents a directed graph using
  4. // adjacency list representation
  5. public class Graph
  6. {
  7. private const int INF = 2147483647;
  8. private int V;
  9. private List<int[]>[] adj;
  10. public Graph(int V)
  11. {
  12. // No. of vertices
  13. this.V = V;
  14. // In a weighted graph, we need to store vertex
  15. // and weight pair for every edge
  16. this.adj = new List<int[]>[V];
  17. for (int i = 0; i < V; i++)
  18. {
  19. this.adj[i] = new List<int[]>();
  20. }
  21. }
  22. public void AddEdge(int u, int v, int w)
  23. {
  24. this.adj[u].Add(new int[] { v, w });
  25. this.adj[v].Add(new int[] { u, w });
  26. }
  27. // Prints shortest paths from src to all other vertices
  28. public void ShortestPath(int src)
  29. {
  30. // Create a priority queue to store vertices that
  31. // are being preprocessed.
  32. SortedSet<int[]> pq = new SortedSet<int[]>(new DistanceComparer());
  33. // Create an array for distances and initialize all
  34. // distances as infinite (INF)
  35. int[] dist = new int[V];
  36. for (int i = 0; i < V; i++)
  37. {
  38. dist[i] = INF;
  39. }
  40. // Insert source itself in priority queue and initialize
  41. // its distance as 0.
  42. pq.Add(new int[] { 0, src });
  43. dist[src] = 0;
  44. /* Looping till priority queue becomes empty (or all
  45. distances are not finalized) */
  46. while (pq.Count > 0)
  47. {
  48. // The first vertex in pair is the minimum distance
  49. // vertex, extract it from priority queue.
  50. // vertex label is stored in second of pair (it
  51. // has to be done this way to keep the vertices
  52. // sorted by distance)
  53. int[] minDistVertex = pq.Min;
  54. pq.Remove(minDistVertex);
  55. int u = minDistVertex[1];
  56. // 'i' is used to get all adjacent vertices of a
  57. // vertex
  58. foreach (int[] adjVertex in this.adj[u])
  59. {
  60. // Get vertex label and weight of current
  61. // adjacent of u.
  62. int v = adjVertex[0];
  63. int weight = adjVertex[1];
  64. // If there is a shorter path to v through u.
  65. if (dist[v] > dist[u] + weight)
  66. {
  67. // Updating distance of v
  68. dist[v] = dist[u] + weight;
  69. pq.Add(new int[] { dist[v], v });
  70. }
  71. }
  72. }
  73. // Print shortest distances stored in dist[]
  74. Console.WriteLine("Vertex Distance from Source");
  75. for (int i = 0; i < V; ++i)
  76. Console.WriteLine(i + "\t" + dist[i]);
  77. }
  78. private class DistanceComparer : IComparer<int[]>
  79. {
  80. public int Compare(int[] x, int[] y)
  81. {
  82. if (x[0] == y[0])
  83. {
  84. return x[1] - y[1];
  85. }
  86. return x[0] - y[0];
  87. }
  88. }
  89. }
  90. public class Program
  91. {
  92. // Driver Code
  93. public static void Main()
  94. {
  95. // create the graph given in above figure
  96. int V = 9;
  97. Graph g = new Graph(V);
  98. // making above shown graph
  99. g.AddEdge(0, 1, 4);
  100. g.AddEdge(0, 7, 8);
  101. g.AddEdge(1, 2, 8);
  102. g.AddEdge(1, 7, 11);
  103. g.AddEdge(2, 3, 7);
  104. g.AddEdge(2, 8, 2);
  105. g.AddEdge(2, 5, 4);
  106. g.AddEdge(3, 4, 9);
  107. g.AddEdge(3, 5, 14);
  108. g.AddEdge(4, 5, 10);
  109. g.AddEdge(5, 6, 2);
  110. g.AddEdge(6, 7, 1);
  111. g.AddEdge(6, 8, 6);
  112. g.AddEdge(7, 8, 7);
  113. g.ShortestPath(0);
  114. }
  115. }
  116. // this code is contributed by bhardwajji

Javascript:

  1. <script>
  2. // javascript Program to find Dijkstra's shortest path using
  3. // priority_queue in STL
  4. const INF = 2147483647;
  5. // This class represents a directed graph using
  6. // adjacency list representation
  7. class Graph {
  8. constructor(V){
  9. // No. of vertices
  10. this.V = V;
  11. // In a weighted graph, we need to store vertex
  12. // and weight pair for every edge
  13. this.adj = new Array(V);
  14. for(let i = 0; i < V; i++){
  15. this.adj[i] = new Array();
  16. }
  17. }
  18. addEdge(u, v, w)
  19. {
  20. this.adj[u].push([v, w]);
  21. this.adj[v].push([u, w]);
  22. }
  23. // Prints shortest paths from src to all other vertices
  24. shortestPath(src)
  25. {
  26. // Create a priority queue to store vertices that
  27. // are being preprocessed. This is weird syntax in C++.
  28. // Refer below link for details of this syntax
  29. // https://www.geeksforgeeks.org/implement-min-heap-using-stl/
  30. let pq = [];
  31. // Create a vector for distances and initialize all
  32. // distances as infinite (INF)
  33. let dist = new Array(V).fill(INF);
  34. // Insert source itself in priority queue and initialize
  35. // its distance as 0.
  36. pq.push([0, src]);
  37. dist[src] = 0;
  38. /* Looping till priority queue becomes empty (or all
  39. distances are not finalized) */
  40. while (pq.length > 0) {
  41. // The first vertex in pair is the minimum distance
  42. // vertex, extract it from priority queue.
  43. // vertex label is stored in second of pair (it
  44. // has to be done this way to keep the vertices
  45. // sorted distance (distance must be first item
  46. // in pair)
  47. let u = pq[0][1];
  48. pq.shift();
  49. // 'i' is used to get all adjacent vertices of a
  50. // vertex
  51. for(let i = 0; i < this.adj[u].length; i++){
  52. // Get vertex label and weight of current
  53. // adjacent of u.
  54. let v = this.adj[u][i][0];
  55. let weight = this.adj[u][i][1];
  56. // If there is shorted path to v through u.
  57. if (dist[v] > dist[u] + weight) {
  58. // Updating distance of v
  59. dist[v] = dist[u] + weight;
  60. pq.push([dist[v], v]);
  61. pq.sort((a, b) =>{
  62. if(a[0] == b[0]) return a[1] - b[1];
  63. return a[0] - b[0];
  64. });
  65. }
  66. }
  67. }
  68. // Print shortest distances stored in dist[]
  69. document.write("Vertex Distance from Source");
  70. for (let i = 0; i < V; ++i)
  71. document.write(i, " ", dist[i]);
  72. }
  73. }
  74. // Driver's code
  75. // create the graph given in above figure
  76. let V = 9;
  77. let g = new Graph(V);
  78. // making above shown graph
  79. g.addEdge(0, 1, 4);
  80. g.addEdge(0, 7, 8);
  81. g.addEdge(1, 2, 8);
  82. g.addEdge(1, 7, 11);
  83. g.addEdge(2, 3, 7);
  84. g.addEdge(2, 8, 2);
  85. g.addEdge(2, 5, 4);
  86. g.addEdge(3, 4, 9);
  87. g.addEdge(3, 5, 14);
  88. g.addEdge(4, 5, 10);
  89. g.addEdge(5, 6, 2);
  90. g.addEdge(6, 7, 1);
  91. g.addEdge(6, 8, 6);
  92. g.addEdge(7, 8, 7);
  93. // Function call
  94. g.shortestPath(0);
  95. // The code is contributed by Nidhi goel.
  96. </script>

输出:

时间复杂度:O(V^2)

辅助空间:O(V)

注意:

· 该代码计算了最短距离,但没有计算路径信息。可以创建一个父节点数组,在更新距离时更新父节点数组,并使用它来显示从源到不同节点的最短路径。

· 该实现的时间复杂度是O(V^2)。如果使用邻接表表示输入图,可以借助二叉堆将其减少为O(E * log V)。更多详情,请参阅邻接表表示的Dijkstra算法。

· Dijkstra算法对具有负权重环的图不起作用。

03 Dijkstra算法的应用

谷歌地图使用Dijkstra算法显示起点和目标点之间的最短距离。

在计算机网络中,Dijkstra算法是各种路由协议的基础,例如OSPF(开放最短路径优先)和IS-IS(中间系统到中间系统)。

交通和交通管理系统使用Dijkstra算法来优化交通流量,减少拥堵,并计划车辆的最高效路径。

航空公司使用Dijkstra算法来规划最小化燃料消耗、减少旅行时间的飞行路径。

Dijkstra算法在电子设计自动化中用于在集成电路和大规模集成(VLSI)芯片上进行路由连接。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/710946
推荐阅读
相关标签
  

闽ICP备14008679号