Dijkstra算法的c++实现
时间: 2024-06-19 10:04:47 浏览: 97
Dijkstra算法是一种常用的单源最短路径算法,用于计算一个节点到其他所有节点的最短路径。以下是Dijkstra算法的C++实现:
```cpp
#include <iostream>
#include <limits.h>
#include <queue>
#include <vector>
using namespace std;
#define V 5 //节点个数
int minDistance(int dist[], bool sptSet[]) //找到当前距离最短的节点
{
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (sptSet[v] == false && dist[v] <= min) {
min = dist[v], min_index = v;
}
}
return min_index;
}
void printSolution(int dist[]) //打印最短路径结果
{
cout << "Vertex \t Distance from Source" << endl;
for (int i = 0; i < V; i++) {
cout << i << "\t\t" << dist[i] << endl;
}
}
void dijkstra(int graph[V][V], int src) //Dijkstra算法实现
{
int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX, sptSet[i] = false;
}
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++) {
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
printSolution(dist);
}
int main()
{
int graph[V][V] = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };
dijkstra(graph, 0);
return 0;
}
```
阅读全文