Floyd算法求最短路径代码

#include <iostream>
#include <cstdio>
#include <climits>

using namespace std;

//floyd算法的实现,利用邻接矩阵存储

const int MAXN = 500 + 10;
const int INF = INT_MAX;

int graph[MAXN][MAXN];
int dis[MAXN][MAXN];

void Floyd(int n) {
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n; ++j) {
            for (int k = 1; k <= n; ++k) {
                dis[i][j] = min(dis[i][j], graph[i][k] + graph[k][j]);
            }
        }
    }
    return;
}

int main() {
    int n;
    while (scanf("%d", &n) != EOF) {
        for (int i = 1; i <= n; ++i) {
            for (int j = 1; j <= n; ++j) {
                scanf("%d", &graph[i][j]);      //输入矩阵
                if (i == j) {
                    dis[i][j] = 0;      //初始化dis矩阵
                } else {
                    dis[i][j] = INF;
                }
            }
        }
        Floyd(n);
        for (int i = 1; i <= n; ++i) {
            for (int j = 1;j <= n; ++j) {
                printf("%d ", dis[i][j]);
            }
            printf("\n");
        }
    }
    return 0;
}
全部评论

相关推荐

AFBUFYGRFHJLP:直接去美帝试试看全奖phd吧
点赞 评论 收藏
分享
微风不断:兄弟,你把四旋翼都做出来了那个挺难的吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务