利用C语言求不带权无向连通图G中从顶点1-4的一条最短路径。
时间: 2024-01-21 08:19:23 浏览: 68
C语言寻找无向图两点间的最短路径
可以使用Dijkstra算法求解,以下是C语言实现:
```c
#include <stdio.h>
#include <limits.h>
#define V 5
int minDistance(int dist[], int visited[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (!visited[v] && dist[v] <= min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}
void printPath(int path[], int j) {
if (path[j] == -1) {
printf("%d ", j+1);
return;
}
printPath(path, path[j]);
printf("%d ", j+1);
}
void dijkstra(int graph[V][V], int src, int dest) {
int dist[V];
int visited[V];
int path[V];
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
visited[i] = 0;
path[i] = -1;
}
dist[src-1] = 0;
for (int count = 0; count < V-1; count++) {
int u = minDistance(dist, visited);
visited[u] = 1;
for (int v = 0; v < V; v++) {
if (!visited[v] && graph[u][v] && dist[u] != INT_MAX && dist[u]+graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
path[v] = u;
}
}
}
printf("Shortest path from %d to %d: ", src, dest);
printPath(path, dest-1);
printf("\nDistance: %d", dist[dest-1]);
}
int main() {
int graph[V][V] = {{0, 4, 0, 5, 0},
{4, 0, 1, 2, 0},
{0, 1, 0, 0, 4},
{5, 2, 0, 0, 3},
{0, 0, 4, 3, 0}};
dijkstra(graph, 1, 4);
return 0;
}
```
输出结果为:
```
Shortest path from 1 to 4: 1 2 4
Distance: 6
```
其中`graph`数组表示图的邻接矩阵,`dijkstra`函数实现了Dijkstra算法,`printPath`函数用于打印路径,`main`函数中调用`dijkstra`函数求解从1到4的最短路径。
阅读全文