/* ******************************************************************************
* Name: BellmanFord
* Description : Find the shortest path from the start point to all other points
* Parameter list: edge - adjacency matrix of the graph
* dist - array of the shortest distance from start point
* path - array of the shortest path
* order - the number of the vertex
* start - start point
* maxNum - max distance means there is no path
******************************************************************************* */
void BellmanFord( int * edge, int * dist, int * path, const int order, const int start, const int maxNum)
{
for ( int i = 0 ; i < order; i ++ )
{
dist[i] = * (edge + start * order + i);
if (dist[i] < maxNum && i != start)
path[i] = start;
else
path[i] = - 1 ;
}
bool isChanged = true ;
for ( int k = 2 ; (k < order) && isChanged; k ++ )
{
isChanged = false ;
for ( int i = 0 ; i < order; i ++ )
{
for ( int j = 0 ; j < order; j ++ )
{
if (dist[i] > dist[j] + * (edge + j * order + i))
{
dist[i] = dist[j] + * (edge + j * order + i);
path[i] = j;
isChanged = true ;
}
}
}
}
}
const int maxNum = 1e8;
int edge[ 7 ][ 7 ] =
{
{ 0 , 6 , 5 , 5 , maxNum, maxNum, maxNum},
{maxNum, 0 , maxNum, maxNum, - 1 , maxNum, maxNum},
{maxNum, - 2 , 0 , maxNum, 1 , maxNum, maxNum},
{maxNum, maxNum, - 2 , 0 , maxNum, - 1 , maxNum},
{maxNum, maxNum, maxNum, maxNum, 0 , maxNum, 3 },
{maxNum, maxNum, maxNum, maxNum, maxNum, 0 , 3 },
{maxNum, maxNum, maxNum, maxNum, maxNum, maxNum, 0 }
};
int dist[ 7 ];
int path[ 7 ];
BellmanFord(( int * )edge, dist, path, 7 , 0 , maxNum);