floyd和warshall算法(作业)

来源:互联网 发布:java web项目开发2017 编辑:程序博客网 时间:2024/06/13 11:03

floyd算法的实现:

#include <stdio.h>#include <stdlib.h>int n, dist[10][10];                                   //矩阵中的数字:999表示不可达,无穷大void printDist();void floyd()                                  //floyd实现算法{    int i, j, k;    for(k = 0; k < n; ++k){        printDist();        for(i = 0; i < n; ++i){            for(j = 0; j < n; ++j){                if (i != j&&dist[i][k]!=999&&dist[k][j]!=999&&dist[i][k] + dist[k][j] < dist[i][j])                {                    dist[i][j] = dist[i][k] + dist[k][j];                }            }        }    }    printDist();}void printDist()                                         //打印矩阵{    int i, j;    printf("   +");    for(i = 0; i < n; ++i)                                     printf("%4c", 65 + i);                         //ASCII码打印字符    printf("\n");    for(i = 0; i < n; ++i){        printf("%4c", 65 + i);        for(j = 0; j < n; ++j){            printf("%4d", dist[i][j]);        }        printf("\n");    }    printf("\n");}int main(void)                                                                            //主函数{    FILE *fin = fopen("floydInput.txt", "r");    fscanf(fin, "%d", &n);    int i, j;    for(i = 0; i < n; ++i){        for(j = 0; j < n; ++j){            fscanf(fin, "%d", &dist[i][j]);        }    }    floyd();    fclose(fin);    getchar();    getchar();    exit(0);}

floydinput.txt

4
0 999 3 999
2 0 999 999
999 7 0 1 
6 999 999 0

2.warshall的实现
#include <stdio.h>#include <stdlib.h>int n, dist[10][10];void printDist();void warshall(){    int i, j, k;    for(k = 0; k < n; ++k){        printDist();        for(i = 0; i < n; ++i){            for(j = 0; j < n; ++j){                if ( dist[i][k]&&dist[k][j])                {                            dist[i][j] = 1;                }            }        }    }}void printDist(){    int i, j;    printf("   +");    for(i = 0; i < n; ++i)        printf("%4c", 65 + i);    printf("\n");    for(i = 0; i < n; ++i){        printf("%4c", 65 + i);        for(j = 0; j < n; ++j){            printf("%4d", dist[i][j]);        }        printf("\n");    }    printf("\n");}int main(void){    FILE *fin = fopen("warshallInput.txt", "r");    fscanf(fin, "%d", &n);    int i, j;    for(i = 0; i < n; ++i){        for(j = 0; j < n; ++j){            fscanf(fin, "%d", &dist[i][j]);        }    }   warshall();    printDist();    fclose(fin);    getchar();    getchar();    getchar();    exit(0);}

warshallInput.txt
4
0 1 0 0
0 0 0 1
0 0 0 0
1 0 1 0


原创粉丝点击