floyd算法求最短路径c
时间: 2023-12-10 17:33:30 浏览: 136
以下是使用C语言实现Floyd算法求最短路径的示例代码:
```c
#include <stdio.h>
#define INF 99999
void floyd(int graph[][4], int n) {
int dist[n][n], i, j, k;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
dist[i][j] = graph[i][j];
}
}
for (k = 0; k < n; k++) {
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
printf("最短路径矩阵:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (dist[i][j] == INF) {
printf("INF ");
} else {
printf("%d ", dist[i][j]);
}
}
printf("\n");
}
}
int main() {
int graph[4][4] = {{0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}};
floyd(graph, 4);
return 0;
}
```
输出结果为:
```
最短路径矩阵:
0 5 8 9
INF 0 3 4
INF INF 0 1
INF INF INF 0
```
阅读全文