c++用邻接矩阵实现Dijkstra算法
时间: 2024-02-12 14:05:12 浏览: 72
C++实现Dijkstra(迪杰斯特拉)算法
以下是C++使用邻接矩阵实现Dijkstra算法的示例代码:
```c++
#include <iostream>
#include <limits.h>
#define V 9
// 找到距离最小的未访问节点
int min_distance(int dist[], bool visited[]) {
int min_dist = INT_MAX, min_index = -1;
for (int v = 0; v < V; v++) {
if (!visited[v] && dist[v] <= min_dist) {
min_dist = dist[v];
min_index = v;
}
}
return min_index;
}
// 打印最短路径
void print_path(int parent[], int j) {
if (parent[j] == -1) {
std::cout << j << " ";
return;
}
print_path(parent, parent[j]);
std::cout << j << " ";
}
// Dijkstra算法
void dijkstra(int graph[V][V], int src) {
int dist[V], parent[V];
bool visited[V];
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
visited[i] = false;
parent[i] = -1;
}
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = min_distance(dist, visited);
visited[u] = true;
for (int v = 0; v < V; v++) {
if (!visited[v] && graph[u][v] && dist[u] != INT_MAX &&
dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
parent[v] = u;
}
}
}
std::cout << "最短路径:" << std::endl;
for (int i = 0; i < V; i++) {
std::cout << src << " -> " << i << " 距离:" << dist[i] << " 路径:";
print_path(parent, i);
std::cout << std::endl;
}
}
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;
}
```
上述代码中,我们使用邻接矩阵表示图,dist数组存储源点到各个节点的距离,parent数组存储最短路径上每个节点的前驱节点,visited数组表示该节点是否被访问过。在Dijkstra算法中,我们通过找到距离最小的未访问节点,以及对其邻接点进行松弛操作,来逐步求解源点到各个节点的最短距离。最后打印出最短路径和距离即可。
阅读全文