迪杰斯特拉算法
辅助数组:
- S[100]用来存放,未加入到最短路径中的结点;
- Path[100]用来存放每个结点的前驱结点,初始时,如果vi到vj有边,vj的前驱就为i,否则为-1;
- D[100]用来存放vi到vj的距离
void ShortTestPath_DIJ(Graph T,int v0)
{
int S[100],Path[100],D[100];
int n = T.Vex_num;
for(int i = 1; i <= n; i++)
{
S[i] = 0;
D[i] = T.Arr[v0][i];
if(D[i] == 100)
Path[i] = -1;
else
Path[i] = v0;
}
S[v0] = 1;D[v0] = 0;
for(int i = 1; i < n; i++)
{
int Min = 100,index;
for(int j = 1; j <= n; j++)
{
if(D[j] < Min && S[j] != 1)
{
Min = D[j];index = j;
}
}
S[index] = 1;
for(int j = 1; j <= n; j++)
{
if(S[j] == 0 && D[index] + T.Arr[index][j] < D[j])
{
D[j] = D[index] + T.Arr[index][j];
Path[j] = index;
}
}
}
for(int i = 1; i <= T.Vex_num; i++)
{
int arr[100];
if(Path[i] != -1)
{
cout<<T.Name[i]<<"\t";
int n = Path[i];
while(n != -1)
{
cout<<T.Name[n]<<"\t";
n = Path[n];
}
cout<<"distance : "<<D[i];
cout<<endl;
}
}
}
弗洛伊德算法
void ShortTestPath_floyd(Graph T)
{
void Get_Path(int i, int j, int path[][100]);
int path[100][100];
int D[100][100];
for(int i = 1; i <= T.Vex_num; i++)
{
for(int j = 1; j <= T.Vex_num; j++)
{
D[i][j] = T.Arr[i][j];
if(D[i][j] < 100)
path[i][j] = i;
else
path[i][j] = -1;
}
}
for(int i = 1; i <= T.Vex_num; i++)
{
for(int j = 1; j <= T.Vex_num; j++)
{
for(int k = 1; k <= T.Vex_num; k++)
{
if(D[j][k] > D[j][i] + D[i][k])
{
D[j][k] = D[j][i] + D[i][k];
path[j][k] = path[i][k];
}
}
}
}
for(int i = 1; i < T.Vex_num; i++)
{
for(int j = 1; j <= T.Vex_num; j++)
{
if(D[i][j] != 100)
{
cout<<T.Name[i]<<"------>"<<T.Name[j]<<"\t";
Get_Path(i,j,path);
cout<<endl;
}
}
}
}
void Get_Path(int i, int j, int path[][100])
{
if(path[i][j] == i){
cout<<T.Name[i]<<" "<<T.Name[j]<<" ";
}else{
Get_Path(i,path[i][j],path);
cout<<T.Name[j]<<" ";
}
}