Last active
October 30, 2017 22:59
-
-
Save sunprinceS/03c1528da78d62a5eaf485be79a7d381 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Floyd Warshall algorithm | |
@Arg: graph data structure defined in graph.h | |
@Return: shortest distance table, dist[i][j] = min. cost from i to j | |
**/ | |
std::vector<std::vector<int> > floyd_warshall(const Graph& g){ | |
std::vector<std::vector<int> > dist(g.num_v,std::vector<int>(g.num_v,INT_MAX)); | |
// Init | |
for(std::size_t i=0;i<g.num_v;++i) | |
dist[i][i] = 0; | |
for(auto it:g.edges){ | |
// there can be negative self cycle | |
if(dist[it.edge.first][it.edge.second] > it.weight) | |
dist[it.edge.first][it.edge.second] = it.weight; | |
} | |
//Recursive, do twice to detect all negative cycles | |
for(std::size_t t=0;t<2;++t){ | |
// d_{ij}^k: the cost of shortest path from i to j using only 0~k-th nodes | |
for(std::size_t k=0;k<g.num_v;++k){ | |
for(std::size_t i=0;i<g.num_v;++i){ | |
for(std::size_t j=0;j<g.num_v;++j){ | |
if(dist[i][k] != INT_MAX && dist[k][j] != INT_MAX){ | |
// No negative cycles | |
if(dist[i][k] != INT_MIN && dist[k][j] != INT_MIN){ | |
//shortest path go through k | |
if(dist[i][k] + dist[k][j] < dist[i][j]) | |
dist[i][j] = dist[i][k] + dist[k][j]; | |
} | |
else | |
dist[i][j] = INT_MIN; | |
//Negative self cycle | |
if(i==j && dist[i][j] < 0) | |
dist[i][j] = INT_MIN; | |
} | |
} | |
} | |
} | |
} | |
return dist; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment