本博文源于浙江大学《数据结构》,先讲一下测试用例
这就是这张图,输入case应该都懂,先输入结点,然后输入边
7 12
2 0 4
2 5 5
0 1 2
0 3 1
1 4 10
1 3 3
3 2 2
3 5 8
3 6 4
3 4 2
4 6 6
6 5 1
我把floyd算法用到的数组在BuildGraph初始化了,大家应该能明白,注意在初始化要正无穷的实现,其他的难点在于这种图如何读
比如我要看V0到V5这个结点的花费,你会发现,只需要调用e[0][5]即可,就是这么简单粗暴。下面是完整的代码:
//floyd算法
//实现有权图单源最短路径问题
//实现无权图单源最短路径邻接矩阵实现
#include<stdio.h>
#include<stdlib.h>
#define MaxVertexNum 10
#define false 0
#define true 1
#define INFINITY 65535
#define ERROR -65535
typedef int WeiGraphhtType;
typedef int DataType;
typedef struct GraphNode *PtrToGraphNode;
typedef int bool;
typedef int Position;
typedef int WeightType;
typedef int ElementType;
int Visited[MaxVertexNum]={false};
int e[10][10];//folyd遍历专用数组
struct GraphNode {
int Nv; //一张图的顶点数
int Ne; //一张图的边数
WeiGraphhtType Graph[MaxVertexNum][MaxVertexNum];
DataType Data[MaxVertexNum];//存顶点的数据
};
typedef PtrToGraphNode MGraphraph;//以邻接矩阵存储的图类型
//初始化一个有VertexNum 个顶点但没有边的图
typedef int Vertex;//用顶点下标表示顶点,为整型
MGraphraph CreateGraphraph(int VertexNum)
{
Vertex V, W;
MGraphraph Graphraph;
Graphraph = (MGraphraph)malloc(sizeof(struct GraphNode));
Graphraph->Nv = VertexNum;
Graphraph->Ne = 0;
//注意:这里默认顶点编号从0开始,到(Graphraph->Nv-1)
for(V=0; V<Graphraph->Nv;V++)
for(W=0; W<Graphraph->Nv;W++)
Graphraph->Graph[V][W] = 0;
for(int i =0;i<Graphraph->Nv;i++)
{
Visited[i]=false;
Graphraph->Data[i]=i;
}
return Graphraph;
}
typedef struct ENode *PtrToENode;
struct ENode {
Vertex V1,V2;//有向边<V1,V2>
WeiGraphhtType WeiGraphht;//权值
};
typedef PtrToENode EdGraphe;
void InsertEdGraphe(MGraphraph Graphraph, EdGraphe E)
{
Graphraph->Graph[E->V1][E->V2] = E->WeiGraphht;
}
MGraphraph BuildGraphraph()
{
MGraphraph Graphraph;
EdGraphe E;
Vertex V;
int Nv,i,j;
scanf("%d",&Nv);
Graphraph = CreateGraphraph(Nv);
scanf("%d",&(Graphraph->Ne));
int inf = 999999;
for(i=0;i<Nv;i++)
for(j=0;j<Nv;j++)
if(i==j)
e[i][j] = 0;
else
e[i][j] = inf;
if(Graphraph->Ne != 0) {
E = (EdGraphe)malloc(sizeof(struct ENode));
for(i=0;i<Graphraph->Ne;i++) {
scanf("%d %d %d",&E->V1,&E->V2,&E->WeiGraphht);
InsertEdGraphe(Graphraph, E);
e[E->V1][E->V2] = E->WeiGraphht;
}
}
return Graphraph;
}
void Floyd(MGraphraph Graph)
{
int i,j,k,t1,t2,t3,n,m;
int inf = 999999;
int Nv = Graph->Nv;
for(k=0;k<Nv;k++)
for(i=0;i<Nv;i++)
for(j=0;j<Nv;j++)
if(e[i][k] < inf && e[k][j]< inf && e[i][j]> e[i][k] + e[k][j])
e[i][j] = e[i][k] + e[k][j];
for(i=0;i<Nv;i++)
{
for(j=0;j<Nv;j++)
printf("%10d",e[i][j]);
printf("\n");
}
}
int main()
{
MGraphraph Graphraph = BuildGraphraph();
int Nv = Graphraph->Nv;
int D[MaxVertexNum][MaxVertexNum];
int path[MaxVertexNum][MaxVertexNum];
Floyd(Graphraph);
int source,destination;
source = 0;
destination = 5;
printf("distance will cost:%d",e[source][destination]);
return 0;
}
如果大家跟着敲的时候,有什么没用到的代码,删去也行,要多去尝试是否能删,精简为美!