我阅读了Wikipedia给出的方法,通过修改 Floyd Warshall 算法在图中以两个给定点打印短路径。我对此进行了编码,但它并没有真正给出预期的输出:
将图中的所有元素初始化
minimumDistanceMatrix[i][j]
为各自的权重,将矩阵中的所有元素初始化shortestPathCalculatorMatrix [i][j]
为-1。然后 :
// Find shortest path using Floyd–Warshall algorithm for ( unsigned int k = 0 ; k < getTotalNumberOfCities() ; ++ k) for ( unsigned int i = 0 ; i < getTotalNumberOfCities() ; ++ i) for ( unsigned int j = 0 ; j < getTotalNumberOfCities() ; ++ j) if ( minimumDistanceMatrix[i][k] + minimumDistanceMatrix[k][j] < minimumDistanceMatrix[i][j] ) { minimumDistanceMatrix[i][j] = minimumDistanceMatrix[i][k] + minimumDistanceMatrix[k][j]; shortestPathCalculatorMatrix [i][j] = k; }
然后 :
void CitiesMap::findShortestPathListBetween(int source , int destination) { if( source == destination || source < 0 || destination < 0) return; if( INFINITY == getShortestPathBetween(source,destination) ) return ; int intermediate = shortestPathCalculatorMatrix[source][destination]; if( -1 == intermediate ) { pathCityList.push_back( destination ); return ; } else { findShortestPathListBetween( source, intermediate ) ; pathCityList.push_back(intermediate); findShortestPathListBetween( intermediate, destination ) ; return ; } }
PS:pathCityList
是一个向量,在调用之前假定为空findShortestPathListBetween
。在此调用结束时,此向量中包含所有中间节点。
有人可以指出我可能会出错的地方吗?