数据结构之无向网邻接矩阵最短路径FLOYD算法—摘抄自《大话数据结构》

#include
using namespace std;
const int MAXEDGE = 20;
const int MAXVEX = 20;
const int INF = 65535;
typedef int Status; /* Status 是函数的类型,其值是函数结果状态代码,如 OK 等 */
typedef struct
{
	int vexs[MAXVEX];
	int arc[MAXVEX][MAXVEX];
	int numVertexes, numEdges;
}MGraph;
typedef int Patharc[MAXVEX][MAXVEX];
typedef int ShortPathTable[MAXVEX][MAXVEX];

void CreateMGraph(MGraph *G)
{
	int i, j;
	/* printf("请输入边数和顶点数:"); */
	G->numEdges = 16;
	G->numVertexes = 9;
	for (i = 0; i < G->numVertexes; i++)/* 初始化图 */
	{
		G->vexs[i] = i;
	}
	for (i = 0; i < G->numVertexes; i++)/* 初始化图 */
	{
		for (j = 0; j < G->numVertexes; j++)
		{
			if (i == j)
				G->arc[i][j] = 0;
			else
				G->arc[i][j] = G->arc[j][i] = INF;
		}
	}
	G->arc[0][1] = 1;
	G->arc[0][2] = 5;
	G->arc[1][2] = 3;
	G->arc[1][3] = 7;
	G->arc[1][4] = 5;
	G->arc[2][4] = 1;
	G->arc[2][5] = 7;
	G->arc[3][4] = 2;
	G->arc[3][6] = 3;
	G->arc[4][5] = 3;
	G->arc[4][6] = 6;
	G->arc[4][7] = 9;
	G->arc[5][7] = 5;
	G->arc[6][7] = 2;
	G->arc[6][8] = 7;
	G->arc[7][8] = 4;
	for (i = 0; i < G->numVertexes; i++)
	{
		for (j = i; j < G->numVertexes; j++)
		{
			G->arc[j][i] = G->arc[i][j];
		}
	}
}
/* Floyd 算法,求网图 G 中各顶点 v 到其余顶点 w 的最短路径 P[v][w]及带权长度 D[v][w]。 */
void ShortestPath_Floyd(MGraph G, Patharc *P, ShortPathTable *D)
{
	int v, w, k;
	for (v = 0; v(*D)[v][k] + (*D)[k][w])
				{/* 如果经过下标为 k 顶点路径比原两点间路径更短 */
					(*D)[v][w] = (*D)[v][k] + (*D)[k][w];/* 将当前两点间权值设为更小的一
														 个 */
					(*P)[v][w] = (*P)[v][k];/* 路径设置为经过下标为 k 的顶点 */
				}
			}
		}
	}
}
int main(void)
{
	int v, w, k;
	MGraph G;
	Patharc P;
	ShortPathTable D; /* 求某点到其余各点的最短路径 */
	CreateMGraph(&G);
	ShortestPath_Floyd(G, &P, &D);
	printf("各顶点间最短路径如下:\n");
	for (v = 0; v %d", k); /* 打印路径顶点 */
				k = P[k][w];  /* 获得下一个路径顶点下标 */
			}
			printf(" -> %d\n", w);  /* 打印终点 */
		}
		printf("\n");
	}
	printf("最短路径 D\n");
	for (v = 0; v

你可能感兴趣的:(数据结构)