所有路径的最短距离(c语言)

来源:互联网 发布:mikumikudance mac版 编辑:程序博客网 时间:2024/06/06 06:58

这里写图片描述

#include<stdio.h>#define MAX 6int n = MAX;int cost[][MAX] = {    {   0,  50,  10,1000,  45,1000},    {1000,   0,  15,1000,  10,1000},    {  20,1000,   0,  15,1000,1000},    {1000,  20,1000,   0,  35,1000},    {1000,1000,  30,1000,   0,1000},    {1000,1000,1000,   3,1000,   0}};//各个点的值int distance[MAX][MAX]={0};//最终距离void allcosts(int cost[][MAX],int distance[][MAX],int n);int main(){    allcosts(cost,distance,n);    for(int i = 0;i < n;i++)    {        for(int j = 0;j < n;j++)        {            printf("%d ",distance[i][j]);        }        putchar('\n');    }}void allcosts(int cost[][MAX],int distance[][MAX],int n){   for(int i = 0;i < n;i++)         for(int j = 0;j < n;j++)            distance[i][j] = cost[i][j];    for(int k = 0;k < n;k++)    //和单源一样,k相当于一个中间点,i到k最短加上k到j最短,就是i到j最短        for(int i = 0;i < n ;i++)            for(int j = 0;j < n;j++)            {                if(distance[i][k]+distance[k][j] < distance[i][j])                    distance[i][j] = distance[i][k] + distance[k][j];            }}

这里写图片描述

阅读全文
0 0
原创粉丝点击