C语言代码实现:采用邻接矩阵存储,实现迪杰斯特拉算法;若规定图中若干个路径必经点,再在原来的基础上改进迪杰斯特拉算法
时间: 2023-08-31 11:24:03 浏览: 92
迪杰斯特拉算法C语言实现
4星 · 用户满意度95%
以下是采用邻接矩阵存储,实现迪杰斯特拉算法,并且规定图中若干个路径必经点的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_VERTICES 100
#define INF INT_MAX
typedef struct GraphType {
int n; // number of vertices
int weight[MAX_VERTICES][MAX_VERTICES];
} GraphType;
void init(GraphType *g) {
g->n = 0;
for (int i = 0; i < MAX_VERTICES; i++) {
for (int j = 0; j < MAX_VERTICES; j++) {
g->weight[i][j] = INF;
}
}
}
void add_edge(GraphType *g, int from, int to, int weight) {
g->weight[from][to] = weight;
}
int dijkstra(GraphType *g, int start, int end, int *required, int num_required) {
int distance[MAX_VERTICES], visited[MAX_VERTICES] = {0};
for (int i = 0; i < g->n; i++) {
distance[i] = INF;
}
// set start vertex distance to 0
distance[start] = 0;
// update distance for all vertices
for (int count = 0; count < g->n - 1; count++) {
int u = -1;
for (int i = 0; i < g->n; i++) {
if (!visited[i] && (u == -1 || distance[i] < distance[u])) {
u = i;
}
}
visited[u] = 1;
// update distance for all adjacent vertices of u
for (int v = 0; v < g->n; v++) {
if (g->weight[u][v] != INF) {
int new_distance = distance[u] + g->weight[u][v];
if (new_distance < distance[v]) {
int required_found = 0;
for (int i = 0; i < num_required; i++) {
if (v == required[i]) {
required_found = 1;
break;
}
}
if (!required_found || (required_found && distance[u] != INF)) {
distance[v] = new_distance;
}
}
}
}
}
return distance[end];
}
int main() {
GraphType g;
init(&g);
// add edges and weights
g.n = 7;
add_edge(&g, 0, 1, 2);
add_edge(&g, 0, 2, 4);
add_edge(&g, 1, 2, 1);
add_edge(&g, 1, 3, 3);
add_edge(&g, 2, 4, 5);
add_edge(&g, 3, 4, 1);
add_edge(&g, 3, 5, 7);
add_edge(&g, 4, 5, 1);
add_edge(&g, 4, 6, 2);
add_edge(&g, 5, 6, 3);
int required[] = {1, 3, 5};
int num_required = 3;
int shortest_distance = dijkstra(&g, 0, 6, required, num_required);
printf("Shortest distance: %d\n", shortest_distance);
return 0;
}
```
在main函数中,我们创建了一个包含7个节点的图,并且添加了相应的边和权重。然后我们调用了dijkstra函数来求从节点0到节点6的最短路径,其中包含必经点1、3、5。在dijkstra函数中,我们首先初始化了距离数组和访问数组,在每次迭代中,我们选择距离源点最近的未访问点,并且更新该点的所有邻接点的距离。如果该点是必经点,并且不满足要求,则不更新该点的距离。最终返回从源点到目标点的最短距离。
注意,在实际应用中,我们可能需要使用更高效的数据结构来存储图,比如邻接表等。
阅读全文