您的位置:首页 > 其它

算法导论 所有节点对的最短路径问题 矩阵法

2017-08-11 16:43 330 查看
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

//图节点
typedef struct VertexNode
{
char name;
VertexNode *p;
}Vertex,*pVertex;

//图
typedef struct
{
int vn;
int **E;
pVertex *V;

}Graph,*pGraph;
//根据算法导论 图25-1 初始化图
pGraph initGraph()
{
pGraph g=(pGraph)malloc(sizeof(Graph));
g->vn=5;
pVertex v1=(pVertex)malloc(sizeof(Vertex));
v1->name='1';
v1->p=NULL;
pVertex v2=(pVertex)malloc(sizeof(Vertex));
v2->name='2';
v2->p=NULL;
pVertex v3=(pVertex)malloc(sizeof(Vertex));
v3->name='3';
v3->p=NULL;
pVertex v4=(pVertex)malloc(sizeof(Vertex));
v4->name='4';
v4->p=NULL;
pVertex v5=(pVertex)malloc(sizeof(Vertex));
v5->name='5';
v5->p=NULL;

g->V=(pVertex*)malloc(g->vn*sizeof(pVertex));
g->V[0]=v1;
g->V[1]=v2;
g->V[2]=v3;
g->V[3]=v4;
g->V[4]=v5;

g->E = (int**)malloc(g->vn*sizeof(int*));
for(int i=0;i<g->vn;i++)
{
g->E[i]=(int*)malloc(g->vn*sizeof(int));
}
for(int i=0;i<g->vn;i++)
{
for(int j=0;j<g->vn;j++)
{
if(i==j)
g->E[i][j]=0;
else
g->E[i][j]=INT_MAX;
}
}
g->E[0][1]=3;
g->E[0][2]=8;
g->E[0][4]=-4;
g->E[1][3]=1;
g->E[1][4]=7;
g->E[2][1]=4;
g->E[3][2]=-5;
g->E[3][0]=2;
g->E[4][3]=6;
return g;
}

int ** ExtendShortestPaths(int **L,int **W,int n)
{
int **P=(int**)malloc(n*sizeof(int*));
for(int i=0;i<n;i++)
{
P[i]=(int*)malloc(n*sizeof(int));
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
P[i][j]=INT_MAX;;
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{
int sum;
if(L[i][k]==INT_MAX || W[k][j]==INT_MAX)
sum=INT_MAX;
else
sum=L[i][k]+W[k][j];
if(P[i][j]>sum)
P[i][j]=sum;
}
}
}
return P;
}

int ** AllPathShortestPaths(int **W,int n)
{
int **L=(int**)malloc(n*sizeof(int*)),**temp;
for(int i=0;i<n;i++)
{
L[i]=(int*)malloc(n*sizeof(int));
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
L[i][j]=W[i][j];
}
}
temp=L;
int m=1;
while(m<n-1)
{
L=ExtendShortestPaths(L,L,n);
m*=2;
free(temp);
temp=L;
}
return L;
}

void printRec(int **L,int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(L[i][j]<INT_MAX)
printf("%2d ",L[i][j]);
else
printf("%2c ",'*');
}
printf("\n");
}
}

void main()
{
pGraph g=initGraph();
int **L=AllPathShortestPaths(g->E,g->vn);
printRec(L,g->vn);
getchar();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: