用dijkstra算法求最短路径问题,输入顶点数,输入权值,输入出发顶点,输出路径,C语言
时间: 2023-08-14 10:02:10 浏览: 90
下面是一个使用 Dijkstra 算法求解单源最短路径的 C 语言代码,其中图的邻接矩阵表示法。
```
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_VERTICES 1000
int graph[MAX_VERTICES][MAX_VERTICES]; // 图的邻接矩阵
int dist[MAX_VERTICES]; // 存储最短路径
int visited[MAX_VERTICES]; // 标记是否访问过该节点
int minDistance(int dist[], int visited[], int n)
{
int min = INT_MAX, min_index;
for (int v = 0; v < n; v++)
{
if (visited[v] == 0 && dist[v] <= min)
{
min = dist[v];
min_index = v;
}
}
return min_index;
}
void dijkstra(int start, int n)
{
for (int i = 0; i < n; i++)
{
dist[i] = INT_MAX;
visited[i] = 0;
}
dist[start] = 0;
for (int count = 0; count < n - 1; count++)
{
int u = minDistance(dist, visited, n);
visited[u] = 1;
for (int v = 0; v < n; 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];
}
}
}
}
int main()
{
int n, start;
printf("Enter the number of vertices: ");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
scanf("%d", &graph[i][j]);
}
}
printf("Enter the starting vertex: ");
scanf("%d", &start);
dijkstra(start, n);
printf("Shortest distances from vertex %d:\n", start);
for (int i = 0; i < n; i++)
{
printf("Vertex %d -> Vertex %d: %d\n", start, i, dist[i]);
}
return 0;
}
```
输入的邻接矩阵应该是一个 $n \times n$ 的矩阵,其中 $n$ 是顶点数。对于从顶点 $i$ 到顶点 $j$ 的边,如果存在,则在矩阵中,$graph[i][j]$ 的值为边的权值,否则为 0。
阅读全文