您的位置:首页 > 理论基础 > 数据结构算法

多源有权图的最短路径 floyd算法(动态规划能解决负权边)7.1.3

2017-04-25 09:13 513 查看
核心代码只有5行呀

for(int k=0;k<Graph->Nv;k++)
for(int i=0;i<Graph->Nv;i++)
for(int j=0;j<Graph->Nv;j++)
if(dist[i][j]>dist[i][k]+dist[k][j])//只要通过中转点能使两点距离变小就更新
{
dist[i][j]=dist[i][k]+dist[k][j];path[i][j]=k;

}
#include<stdlib.h>
#include<stdbool.h>
#include<stdio.h>
#define MaxVertexNum 100    /* 最大顶点数设为100 */
#define INFINITY 65535        /* ∞设为双字节无符号整数的最大值65535*/
typedef int Vertex;         /* 用顶点下标表示顶点,为整型 */
typedef int WeightType;        /* 边的权值设为整型 */
typedef char DataType;        /* 顶点存储的数据类型设为字符型 */
int dist[MaxVertexNum][MaxVertexNum];
int path[MaxVertexNum][MaxVertexNum];
/* 边的定义 */
typedef struct ENode *PtrToENode;
struct ENode{
Vertex V1, V2;      /* 有向边<V1, V2> */
WeightType Weight;  /* 权重 */
};
typedef PtrToENode Edge;

/* 图结点的定义 */
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv;  /* 顶点数 */
int Ne;  /* 边数   */
WeightType G[MaxVertexNum][MaxVertexNum]; /* 邻接矩阵 */
DataType Data[MaxVertexNum];      /* 存顶点的数据 */
/* 注意:很多情况下,顶点无数据,此时Data[]可以不用出现 */
};
typedef PtrToGNode MGraph; /* 以邻接矩阵存储的图类型 */

MGraph CreateGraph( int VertexNum )
{ /* 初始化一个有VertexNum个顶点但没有边的图 */
Vertex V, W;
MGraph Graph;

Graph = (MGraph)malloc(sizeof(struct GNode)); /* 建立图 */
Graph->Nv = VertexNum;
Graph->Ne = 0;
/* 初始化邻接矩阵 */
/* 注意:这里默认顶点编号从0开始,到(Graph->Nv - 1) */
for (V=0; V<Graph->Nv; V++)
for (W=0; W<Graph->Nv; W++)
if(V==W)
Graph->G[V][W]=0;
else
Graph->G[V][W] = INFINITY;

return Graph;
}

void InsertEdge( MGraph Graph, Edge E )  {
/* 插入边 <V1, V2> */
Graph->G[E->V1][E->V2] = E->Weight;
/* 若是无向图,还要插入边<V2, V1> */
Graph->G[E->V2][E->V1] = E->Weight;
}

MGraph BuildGraph()
{
MGraph Graph;
Edge E;
Vertex V;
int Nv, i;

scanf("%d", &Nv);   /* 读入顶点个数 */
Graph = CreateGraph(Nv); /* 初始化有Nv个顶点但没有边的图 */

scanf("%d", &(Graph->Ne));   /* 读入边数 */
if ( Graph->Ne != 0 ) { /* 如果有边 */
E = (Edge)malloc(sizeof(struct ENode)); /* 建立边结点 */
/* 读入边,格式为"起点 终点 权重",插入邻接矩阵 */
for (i=0; i<Graph->Ne; i++) {
scanf("%d %d %d", &E->V1, &E->V2, &E->Weight);
/* 注意:如果权重不是整型,Weight的读入格式要改 */
InsertEdge( Graph, E );
}
free(E);
}

/* 如果顶点有数据的话,读入数据 */
for (V=0; V<Graph->Nv; V++)
scanf(" %c", &(Graph->Data[V]));

return Graph;
}

void Floyd(MGraph Graph){
//初始化
for(int i=0;i<Graph->Nv;i++)
for(int j=0;j<Graph->Nv;j++)
{dist[i][j]=Graph->G[i][j];path[i][j]=-1;}
for(int k=0;k<Graph->Nv;k++)
for(int i=0;i<Graph->Nv;i++)
for(int j=0;j<Graph->Nv;j++)
if(dist[i][j]>dist[i][k]+dist[k][j])
{
dist[i][j]=dist[i][k]+dist[k][j];path[i][j]=k;

}

}

int main(){
MGraph Graph=BuildGraph();
Floyd(Graph);
for(int i=0;i<Graph->Nv;i++){
for(int j=0;j<Graph->Nv;j++)
printf("%d ", dist[i][j]);
printf("\n");

}
for(int i=0;i<Graph->Nv;i++){
for(int j=0;j<Graph->Nv;j++)
printf("%d ", path[i][j]);
printf("\n");

}

return 0;
}

上一篇单源最短路径
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 数据结构