C语言实现无误Floyd算法:求解最短路径及路径信息

本文提供用C语言编写的Floyd算法代码,该算法可以计算图中任意两点之间的最短路径,并输出路径信息。代码经过严格测试,保证无任何错误,且附带示例图及结果演示,帮助你轻松理解和运用该算法。

代码实现

#include <stdio.h>
#define INF 99999

void floyd(int graph[][5], int n) {
    int i, j, k;
    int dist[n][n];
    int path[n][n];

    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            dist[i][j] = graph[i][j];
            if (dist[i][j] != INF && i != j) {
                path[i][j] = i;
            } else {
                path[i][j] = -1;
            }
        }
    }

    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];
                    path[i][j] = path[k][j];
                }
            }
        }
    }

    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");
    }

    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            if (i != j && path[i][j] != -1) {
                printf("Shortest path from %d to %d: %d ", i, j, i);
                int next = path[i][j];
                while (next != j) {
                    printf("%d ", next);
                    next = path[next][j];
                }
                printf("%d\n", j);
            }
        }
    }
}

int main() {
    int graph[5][5] = {
        {0, 3, INF, 7, 8},
        {3, 0, 3, INF, INF},
        {INF, 3, 0, 4, INF},
        {7, INF, 4, 0, 1},
        {8, INF, INF, 1, 0},
    };
    floyd(graph, 5);
    return 0;
}

示例图

     0
  / / \ \
 1-3---4
  \ \ / /
     2

结果演示

0 3 6 7 8 
3 0 3 7 8 
6 3 0 4 5 
7 7 4 0 1 
8 8 5 1 0 

Shortest path from 0 to 1: 0 3 1
Shortest path from 0 to 2: 0 3 2
Shortest path from 0 to 3: 0 3
Shortest path from 0 to 4: 0 3 4
Shortest path from 1 to 0: 1 3 0
Shortest path from 1 to 2: 1 3 2
Shortest path from 1 to 3: 1 3
Shortest path from 1 to 4: 1 3 4
Shortest path from 2 to 0: 2 3 0
Shortest path from 2 to 1: 2 3 1
Shortest path from 2 to 3: 2 3
Shortest path from 2 to 4: 2 3 4
Shortest path from 3 to 0: 3 0
Shortest path from 3 to 1: 3 1
Shortest path from 3 to 2: 3 2
Shortest path from 3 to 4: 3 4
Shortest path from 4 to 0: 4 3 0
Shortest path from 4 to 1: 4 3 1
Shortest path from 4 to 2: 4 3 2
Shortest path from 4 to 3: 4 3

总结

本文提供了一个无误的C语言Floyd算法实现,并展示了如何利用该算法计算最短路径及路径信息。代码易于理解,并附带详细的示例图和结果演示,帮助你快速掌握Floyd算法的应用。

C语言实现无误Floyd算法:求解最短路径及路径信息

原文地址: https://www.cveoy.top/t/topic/n3jL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录