Dijkstra最短路径算法实现代码
本文导语: Dijkstra的最短路径算法是基于前驱顶点的最短路径计算的,整体上来讲还是比较简单的,下面是代码: 代码如下:#include #include #include void shortestpath( const std::vector >& paths, int from, std::vector< short>& path){ std:: vector flags(paths.size...
Dijkstra的最短路径算法是基于前驱顶点的最短路径计算的,整体上来讲还是比较简单的,下面是代码:
#include
#include
#include
void shortestpath( const std::vector >& paths, int from, std::vector< short>& path){
std:: vector flags(paths.size(), false);
std:: vector distance(paths.size(), 0);
path.resize(paths.size(), 0);
for(size_t i = 0; i != paths.size(); ++i){
distance[i] = paths[from][i];
}
flags[from] = 1;
int min, pos;
for(size_t i = 1; i != paths.size(); ++i){
pos = -1;
min = std:: numeric_limits::max();
for(size_t j = 0; j != paths.size(); ++j){
if(!flags[j] && distance[j] < min){
min = distance[j];
pos = j;
}
}
if(pos == -1)
break;
flags[pos] = true;
for(size_t j = 0; j != paths.size(); ++j){
if(!flags[j] && paths[pos][j] != 0
&& paths[pos][j] < std::numeric_limits :: max()
&& min+paths[pos][j] < distance[j]){
distance[j] = min + paths[pos][j];
path[j] = pos;
}
}
}
for(size_t i = 0; i != distance.size(); ++i){
std::cout > vj >> weight;
paths[vi][vj] = weight;
paths[vj][vi] = weight;
}
std:: vector path;
shortestpath(paths, 0, path);
std::cout