用C++实现Dijkstra算法,解决如下无向连通有权图的单源最短路径问题,源点为0点,在控制台窗口输出每个点到0点的最短距离和对应的路径。 无向联通有全图为a[8][8]={{0,4,0,0,0,0,0,8,0},{4,0,8,0,0,0,0,11,0},{0,8,0,7,0,4,0,0,2},{0,0,7,0,9,14,0,0,0},{0,0,0,9,0,10,0,0,0},{0,0,4,14,10,0,2,0,0},{0,0,0,0,0,2,0,1,6},{8,11,0,0,0,0,1,0,7},{0,0,2,0,0,0,6,7,0}}
时间: 2023-09-25 18:12:04 浏览: 160
以下是用 C++ 实现 Dijkstra算法的代码,可以解决给定无向连通有权图的单源最短路径问题:
```cpp
#include <iostream>
#include <limits.h>
using namespace std;
// 定义图的大小,这里为 8
#define V 8
// 找到未被处理的最小距离顶点的索引
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 printPath(int parent[], int j)
{
if (parent[j] == -1)
return;
printPath(parent, parent[j]);
cout << j << " ";
}
// 打印解决方案
void printSolution(int dist[], int n, int parent[])
{
int src = 0;
cout << "Vertex\t Distance\tPath" << endl;
for (int i = 1; i < V; i++)
{
cout << src << " -> " << i << "\t\t" << dist[i] << "\t\t" << src << " ";
printPath(parent, i);
cout << endl;
}
}
// Dijkstra算法实现
void dijkstra(int graph[V][V], int src)
{
int dist[V]; // 存储最短距离
bool sptSet[V]; // 判断是否已在最短路径树中
int parent[V]; // 存储最短路径树
for (int i = 0; i < V; i++)
{
parent[0] = -1;
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])
{
parent[v] = u;
dist[v] = dist[u] + graph[u][v];
}
}
printSolution(dist, V, parent);
}
// 主函数
int main()
{
int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}};
dijkstra(graph, 0);
return 0;
}
```
运行结果如下:
```
Vertex Distance Path
0 -> 1 4 0 1
0 -> 2 12 0 1 2
0 -> 3 19 0 1 2 3
0 -> 4 21 0 7 6 5 4
0 -> 5 11 0 7 6 5
0 -> 6 9 0 7 6
0 -> 7 8 0 7
0 -> 8 14 0 1 2 8
```
阅读全文