#include <iostream.h>
void main()
{
const int m = 1000;
int matric[5][5] =
{
{0,1,m,1,m}, //graph sample { 0--1;0--3;1--2;2--3;2--4;3--4;}
{1,0,1,m,m}, //this is the adjacency matrix
{m,1,0,1,1}, //"0" means the same node to itself
{1,m,1,0,1}, //"1" means there's an edge between the two nodes
{m,m,1,1,0} //"m" means there's no edge between the two nodes
};
int patch[5][5]; //patch
int a[5][5]; //shortest record
int i,j,k,pre;
for (i=0; i<5; i++) //initialization
{
for (j=0; j<5; j++)
{
a[i][j] = matric[i][j];
patch[i][j] = j;
}
}
for (k=0; k<5; k++) //calculate the shortest
{
for (i=0; i<5; i++)
for (j=0; j<5; j++)
{
if(a[i][j] > a[i][k] + a[k][j])
{
a[i][j] = a[i][k] + a[k][j];
patch[i][j] = patch[i][k];
}
}
}
for (i=0; i<5; i++) //printing
for (j=0; j<5; j++)
{
if(a[i][j] == m)
{
cout<<"there is no patch form "<<i<<" to "<<j<<endl;
}
else
{
cout<<"the distance from "<<i<<" to "<<j<<" is "<<a[i][j];
cout<<" the patch is :"<<i;
pre = i;
do
{
pre = patch[pre][j];
cout<<"-->"<<pre;
}while (pre != j);
cout<<endl;
}
}
float total = 0, n = 0;
for (i=0; i<5; i++) //the average path length
for (j=i; j<5; j++)
{
if(a[i][j] == 0 || a[i][j] == m)
total = total;
else
{
total = total + a[i][j];
n++;
}
}
cout<<"the average path length is :"<<(total/n);
cout<<endl;
}
参考资料:I've done it myself, Thanks for your answers.
本回答被提问者采纳