大话数据结构
Unit6 图
邻接矩阵的最短路径Floyd算法
代码
#include <iostream>
typedef char VertexType;
typedef int EdgeType;
#define MAXVEX 10
#define INFINITY 65535
using namespace std;
int visited[100];
typedef int Pathmatirx[MAXVEX][MAXVEX];
typedef int ShortPathTable[MAXVEX][MAXVEX];
//构建顶点表
typedef struct {
VertexType vexs[MAXVEX]; //顶点数组
EdgeType arc[MAXVEX][MAXVEX]; //边的矩阵表示
int numVertexes, numEdges; //图中当前的顶点数和边数
}MGraph;
//创建邻接矩阵
void CreatMgraph(MGraph* G) {
int i, j, k, w;
cout << "输入顶点数和边数:" << endl;
cin >> G->numVertexes >> G->numEdges;
for (i = 0;i < G->numVertexes;i++) {
cout << "请输入顶点名:" << endl;
cin >> G->vexs[i];
}
//初始化邻接矩阵
for (i = 0;i < G->numVertexes;i++) {
for (j = 0;j < G->numVertexes;j++) {
G->arc[i][j] = INFINITY;
}
}
//构建邻接矩阵
for (k = 0;k < G->numEdges;k++) {
cout << "输入边(vi,vj)上的下标i,下标j和权w:" << endl;
cin >> i >> j >> w;
G->arc[i][j] = w;
G->arc[j][i] = G->arc[i][j];
}
}
void ShortestPath_Floyd(MGraph G, Pathmatirx* P, ShortPathTable* D) {
int v, w, k;
for (v = 0;v < G.numVertexes;++v) {
for (w = 0;w < G.numVertexes;++w) {
(*D)[v][w] = G.arc[v][w];
(*P)[v][w] = w;
}
}
for (k = 0;k < G.numVertexes;++k) {
for (v = 0;v < G.numVertexes;++v) {
for (w = 0;w < G.numVertexes;++w) {
if ((*D)[v][w] > (*D)[v][k] + (*D)[k][w]) {
(*D)[v][w] = (*D)[v][k] + (*D)[k][w];
(*P)[v][w] = (*P)[v][k];
}
}
}
}
}
//最短路径的显示代码
void printf_shortPathTable(MGraph G, Pathmatirx* P, ShortPathTable* D) {
int v, w, k;
for (v = 0;v < G.numVertexes;++v) {
for (w = v + 1;w < G.numVertexes;w++) {
cout << v << w << D[v][w];
k = *P[v][w];
cout << v;
while (k != w) {
cout << "->" << k;
k = *P[k][w];
}
cout << "->" << w;
}
cout << endl;
}
}
int main()
{
MGraph* grap = (MGraph*)malloc(sizeof(MGraph));
Pathmatirx* P = (Pathmatirx*)malloc(sizeof(Pathmatirx));
ShortPathTable* D = (ShortPathTable*)malloc(sizeof(ShortPathTable));
CreatMgraph(grap);
ShortestPath_Floyd(*grap,P,D);
//printf_shortPathTable(*grap, P, D);
free(grap);
free(P);
free(D);
grap = NULL;
return 0;
}
运行结果