#include "stdafx.h"
#include <iostream>
#include <list>
// -1 表示无路径可以到达
const static int _VERTEX_NUM =
5;
int arrayPathScheme[ _VERTEX_NUM][_VERTEX_NUM ]
=
{
0, 10, -1, 30, 100,
-1, 0, 50, -1, -1,
-1, -1, 0, -1, 10,
-1, -1, 20, 0, 60,
-1, -1, -1, -1, 0,
};
// 路由算法 有向图的情况下
-1 表示无路径可以达到
enum { EndTag =
-1, };
int _tmain( int argc , _TCHAR* argv[])
{
// 选取输入的顶点
int nSourceVertex =
0; // V0
bool bSelectedVertex [_VERTEX_NUM]; // 是否已被选取到已选取集合之中
for( int i =
0; i < _VERTEX_NUM ;
++i )
bSelectedVertex[i ]
= false;
int nSourceToDestN [_VERTEX_NUM];
for( int i =
0; i< _VERTEX_NUM ;
++i )
{
nSourceToDestN[i ]
= arrayPathScheme [nSourceVertex][ i];
}
bSelectedVertex[nSourceVertex ]
= true;
int nPreVertex [_VERTEX_NUM];
nPreVertex[nSourceVertex ]
= EndTag;
for( int i =
0; i < _VERTEX_NUM ;
++i )
{
if( i != nSourceVertex )
nPreVertex[i ]
= nSourceVertex;
}
// 每次选取一个顶点
n - 1次选取
int nMaxEdgeValue =
10000;
int nMinEdgeValue ;
for( int i =
0; i < _VERTEX_NUM -
1 ; ++i )
{
nMinEdgeValue = nMaxEdgeValue ;
int nDestVertex =
-1;
int nDestEdgeValue =
-1;
for( int j =
0; j < _VERTEX_NUM ;
++j )
{
if( true == bSelectedVertex[ j]
)
continue;
if(
0 == nSourceToDestN [j]
)
continue;
if(
-1 == nSourceToDestN [j]
)
continue;
if( nSourceToDestN [j]
< nMinEdgeValue )
{
nMinEdgeValue
= nSourceToDestN [j];
nDestVertex
= j;
nDestEdgeValue = nSourceToDestN [j];
}
}
// 将该顶点放入集合中
bSelectedVertex[nDestVertex ]
= true;
//
Update nSourceToDest Value
for( int j =
0; j < _VERTEX_NUM ;
++j )
{
if( true == bSelectedVertex[ j]
)
continue;
if( arrayPathScheme [nDestVertex][ j]
== 0 || arrayPathScheme [nDestVertex][ j]
== -1 )
continue;
if( nDestEdgeValue + arrayPathScheme [nDestVertex][ j]
< nSourceToDestN [j]
|| nSourceToDestN [j]
== -1 )
{
nSourceToDestN[j ]
= nDestEdgeValue + arrayPathScheme [nDestVertex][ j];
nPreVertex[j ]
= nDestVertex;
}
}
}
std::list <int> vecPathVertex;
for( int i =
0; i < _VERTEX_NUM ;
++i )
{
vecPathVertex.clear ();
std::cout <<"[
"<< i<<"
]___"<< nSourceToDestN[i ]<<std:: endl;
std::cout <<std:: endl<<"
From " <<nSourceVertex<< "
To "<< i<<"
Shortest Path Is:" <<std:: endl;
int nIndex = i;
while(
1 )
{
vecPathVertex.push_front ( nIndex );
if( nPreVertex [nIndex]
== EndTag )
break;
nIndex = nPreVertex [nIndex];
}
std::list <int>:: iterator iBegin = vecPathVertex .begin();
std::list <int>:: iterator iEnd
= vecPathVertex. end();
for(
; iBegin != iEnd;
++ iBegin )
std::cout <<"
"<<(*iBegin )<<"------";
std::cout <<std:: endl<<std ::endl;
}
system("pause" );
return 0;
}