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

#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();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值