请设计int distance(Graph g,VertexType v, VertexType u)函数。 该函数返回图中两个顶点v和w之间的距离(最短连通路上边的数目)。提示:连通返回距离,不连通返回0。C语言
时间: 2024-02-09 18:10:26 浏览: 110
好的,以下是一个简单的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
#define INF INT_MAX // 无穷大
typedef int VertexType; // 顶点类型
typedef int EdgeType; // 边权类型
// 图的邻接矩阵表示
typedef struct Graph {
int n; // 顶点数
EdgeType **edges; // 边权矩阵
} Graph;
Graph *createGraph(int n) {
Graph *g = (Graph *)malloc(sizeof(Graph));
g->n = n;
g->edges = (EdgeType **)malloc(n * sizeof(EdgeType *));
for (int i = 0; i < n; i++) {
g->edges[i] = (EdgeType *)malloc(n * sizeof(EdgeType));
for (int j = 0; j < n; j++) {
g->edges[i][j] = INF;
}
}
return g;
}
void addEdge(Graph *g, int u, int v, EdgeType w) {
g->edges[u][v] = g->edges[v][u] = w;
}
void destroyGraph(Graph *g) {
for (int i = 0; i < g->n; i++) {
free(g->edges[i]);
}
free(g->edges);
free(g);
}
// 最短路径算法
int distance(Graph *g, VertexType v, VertexType u) {
EdgeType *dist = (EdgeType *)malloc(g->n * sizeof(EdgeType)); // v到各个点的距离
bool *visited = (bool *)malloc(g->n * sizeof(bool)); // 是否访问过
for (int i = 0; i < g->n; i++) {
dist[i] = INF;
visited[i] = false;
}
dist[v] = 0; // 起点到自己的距离为0
for (int k = 0; k < g->n; k++) {
// 找到距离v最近的点
int nearest = -1;
for (int i = 0; i < g->n; i++) {
if (!visited[i] && (nearest == -1 || dist[i] < dist[nearest])) {
nearest = i;
}
}
if (nearest == -1) break;
visited[nearest] = true;
for (int i = 0; i < g->n; i++) { // 遍历所有邻居
if (g->edges[nearest][i] != INF) { // nearest和i有边
if (dist[i] > dist[nearest] + g->edges[nearest][i]) { // 更新距离
dist[i] = dist[nearest] + g->edges[nearest][i];
}
}
}
}
int ret = dist[u] == INF ? 0 : dist[u]; // 返回v到u的距离,若不连通,则返回0
free(dist);
free(visited);
return ret;
}
// 测试
int main() {
Graph *g = createGraph(6);
addEdge(g, 0, 1, 2);
addEdge(g, 0, 2, 5);
addEdge(g, 1, 2, 4);
addEdge(g, 1, 3, 7);
addEdge(g, 1, 4, 5);
addEdge(g, 2, 4, 1);
addEdge(g, 3, 4, 3);
addEdge(g, 3, 5, 2);
addEdge(g, 4, 5, 6);
printf("%d\n", distance(g, 0, 5)); // 输出3
destroyGraph(g);
return 0;
}
```
在这个实现中,我们使用 Dijkstra 算法来计算两个顶点的最短路径距离。如果两个顶点不连通,则返回0。
需要注意的是,在C语言中,需要手动管理内存,因此需要在程序结束时,显式地进行内存释放。
阅读全文