请给出迪杰斯特拉算法c++代码实现
时间: 2023-10-25 13:10:47 浏览: 82
C++实现Dijkstra(迪杰斯特拉)算法
以下是基于邻接矩阵实现的Dijkstra算法的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTEX_NUM 100 // 定义最大节点数
typedef struct {
int vertexNum; // 节点数目
int edgeNum; // 边数目
int matrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; // 邻接矩阵
} Graph;
int minDistance(int dist[], bool visited[], int vertexNum) {
int min = INT_MAX, minIndex;
for (int i = 0; i < vertexNum; i++) {
if (!visited[i] && dist[i] <= min) {
min = dist[i];
minIndex = i;
}
}
return minIndex;
}
void dijkstra(Graph* graph, int start) {
int dist[MAX_VERTEX_NUM];
bool visited[MAX_VERTEX_NUM];
for (int i = 0; i < graph->vertexNum; i++) {
dist[i] = INT_MAX;
visited[i] = false;
}
dist[start] = 0;
for (int i = 0; i < graph->vertexNum - 1; i++) {
int u = minDistance(dist, visited, graph->vertexNum);
visited[u] = true;
for (int v = 0; v < graph->vertexNum; v++) {
if (!visited[v] && graph->matrix[u][v] && dist[u] != INT_MAX
&& dist[u] + graph->matrix[u][v] < dist[v]) {
dist[v] = dist[u] + graph->matrix[u][v];
}
}
}
printf("Vertex\tDistance from Start Vertex\n");
for (int i = 0; i < graph->vertexNum; i++) {
printf("%d\t\t%d\n", i, dist[i]);
}
}
int main() {
Graph* graph = (Graph*)malloc(sizeof(Graph));
printf("Enter the number of vertices: ");
scanf("%d", &graph->vertexNum);
printf("Enter the number of edges: ");
scanf("%d", &graph->edgeNum);
for (int i = 0; i < graph->vertexNum; i++) {
for (int j = 0; j < graph->vertexNum; j++) {
graph->matrix[i][j] = 0;
}
}
printf("Enter the start vertex, end vertex and the weight of each edge:\n");
for (int i = 0; i < graph->edgeNum; i++) {
int start, end, weight;
scanf("%d%d%d", &start, &end, &weight);
graph->matrix[start][end] = weight;
}
int start;
printf("Enter the start vertex: ");
scanf("%d", &start);
dijkstra(graph, start);
free(graph);
return 0;
}
```
该算法的时间复杂度为O(V^2),其中V表示节点数目。如果使用堆优化,则可以将时间复杂度降为O(E + VlogV),其中E表示边数目。
阅读全文