C语言给定带权无向图G和源点D,采用邻接表,利用Dijkstra算法求源点D到其余各个顶点的最短距离的代码。
时间: 2024-02-09 08:09:53 浏览: 75
好的,下面是用C语言实现Dijkstra算法求解带权无向图G的源点D到其他顶点的最短距离的代码。在这个例子中,我们假设用邻接表存储图。
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_VERTICES 100
typedef struct Edge {
int dest;
int weight;
struct Edge* next;
} Edge;
typedef struct Vertex {
Edge* head;
} Vertex;
Vertex graph[MAX_VERTICES];
int dist[MAX_VERTICES];
int visited[MAX_VERTICES];
// 找到距离源点最近的未访问顶点
int get_min_distance(int n)
{
int min_distance = INT_MAX;
int min_vertex = -1;
for (int i = 0; i < n; i++) {
if (!visited[i] && dist[i] < min_distance) {
min_distance = dist[i];
min_vertex = i;
}
}
return min_vertex;
}
void dijkstra(int start, int n)
{
// 初始化距离
for (int i = 0; i < n; i++) {
dist[i] = INT_MAX;
visited[i] = 0;
}
dist[start] = 0;
for (int i = 0; i < n - 1; i++) {
// 找到距离源点最近的未访问顶点
int u = get_min_distance(n);
// 标记该顶点为已访问
visited[u] = 1;
// 更新距离
Edge* curr = graph[u].head;
while (curr != NULL) {
int v = curr->dest;
int weight = curr->weight;
if (!visited[v] && dist[u] != INT_MAX &&
dist[u] + weight < dist[v])
{
dist[v] = dist[u] + weight;
}
curr = curr->next;
}
}
}
void add_edge(int u, int v, int weight)
{
Edge* new_edge = malloc(sizeof(Edge));
new_edge->dest = v;
new_edge->weight = weight;
new_edge->next = graph[u].head;
graph[u].head = new_edge;
}
int main()
{
int n, start;
printf("请输入顶点数和起点编号:");
scanf("%d %d", &n, &start);
printf("请输入边的数量:");
int m;
scanf("%d", &m);
printf("请输入每条边的起点、终点和权值:\n");
for (int i = 0; i < m; i++) {
int u, v, weight;
scanf("%d %d %d", &u, &v, &weight);
add_edge(u, v, weight);
add_edge(v, u, weight);
}
dijkstra(start, n);
printf("源点%d到各顶点的最短距离为:\n", start);
for (int i = 0; i < n; i++) {
printf("%d ", dist[i]);
}
return 0;
}
```
在上面的代码中,我们使用了两个结构体Vertex和Edge来表示邻接表。add_edge函数用来添加边。dijkstra函数实现了Dijkstra算法的核心部分,get_min_distance函数则是用来找到距离源点最近的未访问顶点。最后,我们在主函数中读入图和源点,并调用dijkstra函数即可输出源点D到其他顶点的最短距离。
阅读全文