for (int k = 0; k < G.vCount; ++k) for (int i = 0; i < G.vCount; ++i) for (int j = 0; j < G.vCount; ++j) if (G.arcs[i][j] > G.arcs[i][k] + G.arcs[k][j]) G.arcs[i][j] = G.arcs[i][k] + G.arcs[k][j];
constint Num = 50; constint MaxInt = 32767; structGraph { int vexs[Num]; //顶点表 int arcs[Num][Num]; //边表 int vCount; //顶点数量 int aCount; //边数量 };
//获取值在顶点表中下标 intGetSub(Graph G, int value) { int i; for (i = 0; i < G.vCount; ++i) { if (G.vexs[i] == value) break; } return i; } //创建图(邻接矩阵) voidCreatMap(Graph &G) { int t1, t2, w; //输入顶点信息 for (int i = 0; i < G.vCount; ++i) { cin >> G.vexs[i]; } for (int i = 0; i < G.vCount; ++i) for (int j = 0; j < G.vCount; ++j) { G.arcs[i][j] = MaxInt; if (i == j) G.arcs[i][j] = 0; } for (int i = 0; i < G.aCount; ++i) { cin >> t1 >> t2 >> w; int s1 = GetSub(G, t1); int s2 = GetSub(G, t2); if (s1 != G.vCount && s2 != G.vCount) { G.arcs[s1][s2] = w; //G.arcs[s2][s1] = w; //无向图 } } } //打印图 voidShowGraph(Graph G) { for (int i = 0; i < G.vCount; ++i) { for (int j = 0; j < G.vCount; ++j) { cout << G.arcs[i][j] << "\t"; } cout << endl; } }
//弗洛伊德算法 voidFloyd(Graph G) { for (int k = 0; k < G.vCount; ++k) { for (int i = 0; i < G.vCount; ++i) { for (int j = 0; j < G.vCount; ++j) { if (G.arcs[i][j] > G.arcs[i][k] + G.arcs[k][j]) G.arcs[i][j] = G.arcs[i][k] + G.arcs[k][j]; } } } cout << "任意两点间的最短距离为:" << endl; //打印最终结果 ShowGraph(G); }
/* 迪杰斯特拉算法 G:图 origin:源点(起点) */ voidDijkstra(Graph G, int origin) { //dis:储存源点到其它点的最短距离,book:用来做标记,标记到当前点到源点的最短距离是否已被确定 int *dis = newint[G.vCount], *book = newint[G.vCount]; int i = 0, j = 0, k = 0, s = 0, min = MaxInt; for (i = 0; i < G.vCount; ++i) { //GetSub(G,origin):获取源点在顶点表中的下标 s = GetSub(G, origin); dis[i] = G.arcs[s][i]; } //初始化标记 for (i = 0; i < G.vCount; ++i) { book[i] = 0; } //设置源点到源点的最短距离为已确定 book[s] = 1;
//确定源点到dis表里的所有顶点的最短距离,算法核心 for (i = 1; i < G.vCount; ++i) { min = MaxInt; //在未确定到源点最短距离的顶点中找到离源点最近的顶点 for (j = 1; j < G.vCount; ++j) { if (book[j] == 0 && dis[j] < min) { min = dis[j]; s = j; } } //设置s点到源点的最短距离为已知 book[s] = 1; //对当前顶点的出边进行松弛 for (k = 0; k < G.vCount; ++k) { //判断下标为s的顶点到下标为k的顶点间是否存在边,若存在,对其进行松弛操作 if (G.arcs[s][k] < MaxInt) { if (dis[k] > dis[s] + G.arcs[s][k]) { dis[k] = dis[s] + G.arcs[s][k]; } } } }
//打印最短路径 for (i = 0; i < G.vCount; ++i) { cout << "点" << origin << "到" << G.vexs[i] << "的最短距离为:" << dis[i] << endl; }