用c语言写一段代码,具体要求是实现最短路径算法dijkstra
时间: 2024-02-18 15:00:15 浏览: 162
好的,以下是用C语言实现最短路径算法Dijkstra的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_VERTICES 100
#define INF INT_MAX
typedef struct Edge {
int dest;
int weight;
struct Edge* next;
} Edge;
typedef struct Vertex {
int dist;
int visited;
Edge* edges;
} Vertex;
typedef struct Graph {
int num_vertices;
Vertex vertices[MAX_VERTICES];
} Graph;
int min_dist(Graph* graph) {
int min = INF;
int min_index = -1;
for (int i = 0; i < graph->num_vertices; i++) {
if (!graph->vertices[i].visited && graph->vertices[i].dist < min) {
min = graph->vertices[i].dist;
min_index = i;
}
}
return min_index;
}
void add_edge(Graph* graph, int src, int dest, int weight) {
Edge* edge = (Edge*) malloc(sizeof(Edge));
edge->dest = dest;
edge->weight = weight;
edge->next = graph->vertices[src].edges;
graph->vertices[src].edges = edge;
}
void dijkstra(Graph* graph, int src) {
for (int i = 0; i < graph->num_vertices; i++) {
graph->vertices[i].dist = INF;
graph->vertices[i].visited = 0;
}
graph->vertices[src].dist = 0;
for (int i = 0; i < graph->num_vertices - 1; i++) {
int u = min_dist(graph);
graph->vertices[u].visited = 1;
Edge* edge = graph->vertices[u].edges;
while (edge != NULL) {
int v = edge->dest;
int weight = edge->weight;
if (!graph->vertices[v].visited && graph->vertices[u].dist != INF && graph->vertices[u].dist + weight < graph->vertices[v].dist) {
graph->vertices[v].dist = graph->vertices[u].dist + weight;
}
edge = edge->next;
}
}
}
int main() {
Graph graph;
int num_vertices, num_edges, src;
scanf("%d %d %d", &num_vertices, &num_edges, &src);
graph.num_vertices = num_vertices;
for (int i = 0; i < num_edges; i++) {
int src, dest, weight;
scanf("%d %d %d", &src, &dest, &weight);
add_edge(&graph, src, dest, weight);
add_edge(&graph, dest, src, weight);
}
dijkstra(&graph, src);
for (int i = 0; i < num_vertices; i++) {
printf("Shortest distance from %d to %d is %d\n", src, i, graph.vertices[i].dist);
}
return 0;
}
```
这段代码实现了Dijkstra算法,包括加边、最短路径计算和输出结果等功能。你可以通过输入节点数、边数、起点和每条边的起点、终点和权重来测试这段代码。
阅读全文