#include <stdlib.h>
#include <stdio.h>
#define SIZE 8
#define INFINATE 99999
#define IN_FILE "distance.txt"
int matrix[SIZE][SIZE];
int next[SIZE][SIZE]={0};
/**
* find the shortest path between i and j
*/
void getPath(int i,int j)
{
if(INFINATE==matrix[i][j])
{
printf("no path");
}
int intermediate=next[i][j];
if(0==intermediate)
{
printf(" ");
}
else
{
getPath(i,intermediate);
printf("%d\t",intermediate);
getPath(intermediate,j);
}
printf("\n");
}
/**
* display the final matrix
*/
void printMatrix()
{
int i,j;
for(i=0;i<SIZE;i++)
{
for(j=0;j<SIZE;j++)
{
printf("%d\t",matrix[i][j]);
}
printf("\n");
}
}
void readin()
{
FILE *fpin=fopen(IN_FILE,"r");
if(NULL==fpin)
{
fprintf(stderr,"cannot open file:%s\n",IN_FILE);
exit(0);
}
int i,j;
//read the original matrix into the mem
for(i=0;i<SIZE;i++){
for(j=0;j<SIZE;j++){
fscanf(fpin,"%d\n",&matrix[i][j]);
}
}
}
int main()
{
readin();
printf("original matrix:\n");
printMatrix();
printf("\n");
int k,i,j,sum;
for(k=0;k<SIZE;k++)
{
for(i=0;i<SIZE;i++)
{
for(j=0;j<SIZE;j++)
{
//core center for matrix update
if(INFINATE!=matrix[i][k] && INFINATE!=matrix[k][j])
sum=matrix[i][k]+matrix[k][j];
else
sum=INFINATE;
if(matrix[i][j]>sum)
{
//update the value
matrix[i][j]=sum;
//record the path
next[i][j]=k;
}
}
}
}
printMatrix();
getPath(1,1);
}
最短路径(Floyd_Warshall算法)
最新推荐文章于 2019-03-16 14:49:16 发布