#include <bits/stdc++.h>
using namespace std;
#define max 32767
//地杰斯特拉算法
// define Distance
int *Distance = new int[100];
// define path
int *path = new int[100];
// define set of selected vex
bool *s = new bool[100];
struct AMGraph
{
int m_vexNum,m_arcNum;
char m_vexName[100];
int m_arcWeight[100][100];
};
int locateVex(AMGraph AMG,char vexName)
{
for (int i = 0;i < AMG.m_vexNum;i++)
{
if (AMG.m_vexName[i] == vexName)
return i;
}
return -1;
}
void createAMGraph(AMGraph &AMG)
{
cout << "pls input the num of vex and arc:"<<endl;
cin >> AMG.m_vexNum >> AMG.m_arcNum;
cout << "pls input the vex name"<<endl;
for (int i = 0;i < AMG.m_vexNum;i++)
{
cout << "pls input the "<<(i+1)<<" vex name" << endl;
cin >> AMG.m_vexName[i];
}
// init all the weight of matrix
for (int i = 0;i < AMG.m_vexNum;i++)
{
for (int j = 0;j < AMG.m_vexNum;j++)
{
AMG.m_arcWeight[i][j] = max;
}
}
cout << "pls input arc as a b 10"<<endl;
for (int i = 0;i < AMG.m_arcNum;i++)
{
char vexName1,vexName2;
int weight;
cin >> vexName1 >> vexName2 >> weight;
int m = locateVex(AMG,vexName1);
int n = locateVex(AMG,vexName2);
AMG.m_arcWeight[m][n] = weight;
AMG.m_arcWeight[n][m] = AMG.m_arcWeight[m][n];
}
}
void dijastral(AMGraph AMG,char startVex)
{
int startAdd = locateVex(AMG,startVex);
// init Distance[] s[] path[]
for (int i = 0;i < AMG.m_vexNum;i++)
{
s[i] = false;
Distance[i] = AMG.m_arcWeight[startAdd][i];
if (Distance[i] < max)
{
path[i] = startAdd;
}
else
{
path[i] = -1;
}
}
s[startAdd] = true;
Distance[startAdd] = 0;
for (int i = 1;i < AMG.m_vexNum;i++)
{
int min = max;
for (int j = 0;j < AMG.m_vexNum;j++)
{
if (!s[j] && Distance[j] < min)
{
i = j;
min = Distance[j];
}
}
s[i] = true;
for (int k = 0;k < AMG.m_vexNum;k++)
{
if (!s[k] && Distance[k] > AMG.m_arcWeight[i][k]+Distance[i])
{
Distance[k] = AMG.m_arcWeight[i][k] +Distance[i];
path[k] = i;
}
}
}
}
void showPath(AMGraph AMG,int startVexAdd,int endVexAdd)
{
if (path[endVexAdd] != -1)
{
showPath(AMG,startVexAdd,path[endVexAdd]);
cout << AMG.m_vexName[path[endVexAdd]]<< "-->";
}
}
void test()
{
AMGraph myGraph;
createAMGraph(myGraph);
char startVex,endVex;
cout << "pls input start vex and end vex"<<endl;
cin >> startVex >> endVex;
int startVexAdd = locateVex(myGraph,startVex);
int endVexAdd = locateVex(myGraph, endVex);
dijastral(myGraph,startVex);
cout << "---------------------------------------"<<endl;
showPath(myGraph,startVexAdd,endVexAdd);
cout << endVex << endl;
delete[] Distance;
delete[] path;
delete[] s;
}
int main()
{
test();
system("pause");
return 0;
}
03-07
8万+

04-06
1900
