用C语言构建无向网,并在此基础上求得指定起点和终点的最短路径。
时间: 2024-06-14 21:05:25 浏览: 68
以下是用C语言构建无向网并求得指定起点和终点的最短路径的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_VERTICES 100
#define INFINITY INT_MAX
typedef struct {
int weight;
int v1;
int v2;
} Edge;
typedef struct {
int numVertices;
int numEdges;
int matrix[MAX_VERTICES][MAX_VERTICES];
} Graph;
void initGraph(Graph *graph, int numVertices) {
graph->numVertices = numVertices;
graph->numEdges = 0;
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
graph->matrix[i][j] = INFINITY;
}
}
}
void addEdge(Graph *graph, int v1, int v2, int weight) {
graph->matrix[v1][v2] = weight;
graph->matrix[v2][v1] = weight;
graph->numEdges++;
}
void dijkstra(Graph *graph, int startVertex, int endVertex) {
int distance[MAX_VERTICES];
int visited[MAX_VERTICES];
int previous[MAX_VERTICES];
for (int i = 0; i < graph->numVertices; i++) {
distance[i] = INFINITY;
visited[i] = 0;
previous[i] = -1;
}
distance[startVertex] = 0;
for (int i = 0; i < graph->numVertices - 1; i++) {
int minDistance = INFINITY;
int minVertex = -1;
for (int j = 0; j < graph->numVertices; j++) {
if (!visited[j] && distance[j] < minDistance) {
minDistance = distance[j];
minVertex = j;
}
}
visited[minVertex] = 1;
for (int j = 0; j < graph->numVertices; j++) {
if (!visited[j] && graph->matrix[minVertex][j] != INFINITY) {
int newDistance = distance[minVertex] + graph->matrix[minVertex][j];
if (newDistance < distance[j]) {
distance[j] = newDistance;
previous[j] = minVertex;
}
}
}
}
if (distance[endVertex] == INFINITY) {
printf("No path found from vertex %d to vertex %d\n", startVertex, endVertex);
} else {
printf("Shortest path from vertex %d to vertex %d: ", startVertex, endVertex);
int path[MAX_VERTICES];
int pathLength = 0;
int currentVertex = endVertex;
while (currentVertex != -1) {
path[pathLength++] = currentVertex;
currentVertex = previous[currentVertex];
}
for (int i = pathLength - 1; i >= 0; i--) {
printf("%d ", path[i]);
}
printf("\nShortest path length: %d\n", distance[endVertex]);
}
}
int main() {
Graph graph;
int numVertices, numEdges;
int v1, v2, weight;
int startVertex, endVertex;
printf("Enter the number of vertices: ");
scanf("%d", &numVertices);
initGraph(&graph, numVertices);
printf("Enter the number of edges: ");
scanf("%d", &numEdges);
for (int i = 0; i < numEdges; i++) {
printf("Enter edge %d (v1 v2 weight): ", i + 1);
scanf("%d %d %d", &v1, &v2, &weight);
addEdge(&graph, v1, v2, weight);
}
printf("Enter the start vertex: ");
scanf("%d", &startVertex);
printf("Enter the end vertex: ");
scanf("%d", &endVertex);
dijkstra(&graph, startVertex, endVertex);
return 0;
}
```
阅读全文