算法6.10 迪杰斯特拉算法
代码实现
# pragma once
# include <iostream>
using namespace std;
# define MaxInt 32767
# define MVNum 100
typedef char VerTexType;
typedef int ArcType;
int * D = new int [ MVNum] ;
bool * S = new bool [ MVNum] ;
int * Path = new int [ MVNum] ;
typedef struct
{
VerTexType vexs[ MVNum] ;
ArcType arcs[ MVNum] [ MVNum] ;
int vexnum, arcnum;
} AMGraph;
int LocateVex ( AMGraph G, VerTexType v)
{
for ( int i = 0 ; i < G. vexnum; ++ i)
if ( G. vexs[ i] == v)
return i;
return - 1 ;
}
void CreateUDN ( AMGraph& G)
{
VerTexType v1, v2;
ArcType w;
int row;
int col;
cout << "请输总顶点数:" ;
cin >> G. vexnum;
cout << "请输总边数:" ;
cin >> G. arcnum;
for ( int i = 0 ; i < G. vexnum; i++ )
{
cout << "输入顶点:" ;
cin >> G. vexs[ i] ;
}
for ( int m = 0 ; m < G. vexnum; m++ )
{
for ( int n = 0 ; n < G. vexnum; n++ )
{
G. arcs[ m] [ n] = MaxInt;
}
}
for ( int k = 0 ; k < G. arcnum; k++ )
{
cout << "输入边依附的顶点以及权值:" ;
cin >> v1 >> v2 >> w;
row = LocateVex ( G, v1) ;
col = LocateVex ( G, v2) ;
G. arcs[ row] [ col] = w;
}
}
void ShowGraph ( AMGraph G)
{
cout << "邻接矩阵为:" << endl;
for ( int i = 0 ; i < G. vexnum; i++ )
{
for ( int j = 0 ; j < G. vexnum; j++ )
{
if ( G. arcs[ i] [ j] == MaxInt)
{
cout << "∞" << " " ;
}
else
{
cout << G. arcs[ i] [ j] << " " ;
}
}
cout << endl;
}
}
void ShortestPath_DIJ ( AMGraph G, int v0)
{
int v, i, w, min;
int n = G. vexnum;
for ( v = 0 ; v < n; ++ v)
{
S[ v] = false ;
D[ v] = G. arcs[ v0] [ v] ;
if ( D[ v] < MaxInt)
{
Path[ v] = v0;
}
else
{
Path[ v] = - 1 ;
}
}
S[ v0] = true ;
D[ v0] = 0 ;
for ( i = 1 ; i < n; ++ i)
{
min = MaxInt;
for ( w = 0 ; w < n; ++ w)
{
if ( ! S[ w] && D[ w] < min)
{
v = w;
min = D[ w] ;
}
}
S[ v] = true ;
for ( w = 0 ; w < n; ++ w)
{
if ( ! S[ w] && ( D[ v] + G. arcs[ v] [ w] < D[ w] ) )
{
D[ w] = D[ v] + G. arcs[ v] [ w] ;
Path[ w] = v;
}
}
}
}
void DisplayPath ( AMGraph G, int begin, int temp)
{
if ( Path[ temp] != - 1 )
{
DisplayPath ( G, begin, Path[ temp] ) ;
cout << G. vexs[ Path[ temp] ] << "-->" ;
}
}
int main ( )
{
AMGraph G;
int i, j, num_start, num_destination;
VerTexType start, destination;
CreateUDN ( G) ;
cout << endl;
cout << "*****无向网G创建完成!*****" << endl;
ShowGraph ( G) ;
cout << "请依次输入起始点、终点名称:" ;
cin >> start >> destination;
num_start = LocateVex ( G, start) ;
num_destination = LocateVex ( G, destination) ;
ShortestPath_DIJ ( G, num_start) ;
cout << endl << "最短路径为:" ;
DisplayPath ( G, num_start, num_destination) ;
cout << G. vexs[ num_destination] << endl;
system ( "pause" ) ;
return 0 ;
}
运行结果