根据大话数据结构整理
/**********************************
*输入:邻接矩阵vMatrix
*输出:最短路径
***********************************/
#include <iostream>
#include <vector>
using namespace std;
#define INF 65535
/*********Dijkstra************/
void Dijstra(vector<vector<int>>&Matrix, int v0)
{
vector<int> patharc(Matrix.size());
vector<int> shortPathTable(Matrix.size());
vector<bool> visit(Matrix.size());
for (unsigned i = 0; i < Matrix.size(); i++)
shortPathTable[i] = Matrix[v0][i];
visit[v0] = true;//v0点已访问
for (unsigned v = 1; v < Matrix.size(); v++)//只需要找到n-1个点组成路径
{
//找到所有未访问点最小权值
int min = INF;
int k;
for (unsigned w = 0; w < Matrix.size(); w++)
{
if (!visit[w] && shortPathTable[w] < min)
{
k = w;
min = shortPathTable[w];
}
}
visit[k] = true;
//更新权值
for (unsigned w = 0; w < Matrix.size(); w++)
{
if (!visit[w] && (min + Matrix[k][w] < shortPathTable[w]))
{
shortPathTable[w] = min + Matrix[k][w];
patharc[w] = k;//表示w的前驱点是k
}
}
}
//输出路径
cout << "(Dijstra)顶点" << v0 << "到各点的最短路径:" << endl;
vector<vector<int>> vvOut(Matrix.size());
for (unsigned i = 0; i < vvOut.size(); i++)
{
int end = i;
vvOut[i].push_back(i);
while (end != v0)
{
end = patharc[end];
vvOut[i].push_back(end);
}
if (i == v0)
vvOut[i].push_back(v0);
}
for (unsigned i = 0; i < vvOut.size(); i++)
{
auto iter = vvOut[i].rbegin();
cout << *iter++;
for (; iter != vvOut[i].rend(); iter++)
cout << "->" << *iter;
cout << endl;
}
}
/*********Floyd****************/
void Floyd(vector<vector<int>>&Matrix)
{
//初始化
vector<vector<int>> pathMatrix(Matrix.size(), vector<int>(Matrix.size()));
vector<vector<int>> shortPathTable(Matrix);
for (unsigned v = 0; v < Matrix.size(); v++)
for (unsigned w = 0; w < Matrix.size(); w++)
pathMatrix[v][w] = w;
//3层循环
for (unsigned k = 0; k < Matrix.size(); k++)
{
for (unsigned v = 0; v < Matrix.size(); v++)
{
for (unsigned w = 0; w < Matrix.size(); w++)
{
if (shortPathTable[v][w] > shortPathTable[v][k] + shortPathTable[k][w])
{
shortPathTable[v][w] = shortPathTable[v][k] + shortPathTable[k][w];
pathMatrix[v][w] = pathMatrix[v][k];
}
}
}
}
for (unsigned v = 0; v < Matrix.size(); v++)
{
cout << "(Floyd)顶点" << v << "到各点的最短路径:" << endl;
for (unsigned w = 0; w < Matrix.size(); w++)
{
cout << v;
int end = pathMatrix[v][w];
while (end != w)
{
cout << "->" << end;
end = pathMatrix[end][w];
}
cout << "->" << w << endl;
}
}
}
/*********主函数****************/
int main()
{
int nodeNum, N, data1, data2, data3;
cin >> nodeNum >> N;
/******建立邻接矩阵**********/
vector<vector<int>> vMatrix(nodeNum, vector<int>(nodeNum, INF));
for (int j = 0; j < nodeNum; j++)
vMatrix[j][j] = 0;
for (int i = 0; i < N; i++)
{
cin >> data1 >> data2 >> data3;
vMatrix[data1][data2] = data3;
vMatrix[data2][data1] = data3;
}
Dijstra(vMatrix, 0);
Floyd(vMatrix);
return 0;
}
/*case:顶点数n,边数m,m条边*/
/*
9
15
0 1 10
0 5 11
1 2 18
1 8 12
1 6 16
2 3 22
2 8 8
3 4 20
3 7 16
3 6 24
3 8 21
4 5 26
4 7 7
5 6 17
6 7 19
*/