以邻接表作存储结构,实现求从源点到其余各顶点的最短路径的Dijkstra算法,用c语言伪代码写
时间: 2024-02-13 13:07:48 浏览: 86
以下是使用邻接表和Dijkstra算法求解最短路径的伪代码实现:
```
#define MAX_VERTICES 1000
#define INF 1000000
typedef struct Edge {
int dest;
int weight;
struct Edge* next;
} Edge;
typedef struct Vertex {
Edge* head;
} Vertex;
typedef struct Graph {
Vertex vertices[MAX_VERTICES];
int num_vertices;
} Graph;
void dijkstra(Graph* graph, int source, int dist[]) {
int visited[MAX_VERTICES] = {0};
for (int i = 0; i < graph->num_vertices; i++) {
dist[i] = INF;
}
dist[source] = 0;
for (int i = 0; i < graph->num_vertices - 1; i++) {
int u = -1;
int min_dist = INF;
for (int j = 0; j < graph->num_vertices; j++) {
if (!visited[j] && dist[j] < min_dist) {
u = j;
min_dist = dist[j];
}
}
visited[u] = 1;
Edge* curr = graph->vertices[u].head;
while (curr != NULL) {
int v = curr->dest;
int weight = curr->weight;
if (!visited[v] && dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
}
curr = curr->next;
}
}
}
```
其中,`Graph`表示图,`Vertex`表示顶点,`Edge`表示边。在`dijkstra`函数中,`source`表示源点的编号,`dist`表示最短距离数组。算法的基本思想是:每次选择当前未访问过的距离源点最近的顶点,然后更新该顶点的邻接点的距离。最终,`dist`数组中存储的就是源点到各个顶点的最短距离。
阅读全文