求Graph里两点间最短距离,可以容纳负值边;可以检测出negative circle
int bellmanFord(int n[][N], int start, int dest) {
int dist[N];
int path[N];
int i, j, k;
for(i = 0; i < N; i++) {
dist[i] = -1;
}
dist[dest] = 0;
for(i = 0; i < N - 1; i++) {
for(j = 0; j < N; j++) {
//graph is adjacent matrix, take O(n) time to find the min edge?
int minEdge = 0x0FFFFFFF;
for(k = 0; k < N; k++) {
if(graph[j][k] != -1) {
minEdge = (minEdge > graph[j][k]) ? graph[j][k] : minEdge;
}
}
dist[j] = (dist[j] > dist[j - 1] + minEdge) ? (dist[j - 1] + minEdge) : dist[j];
}
}
return dist[start];
}
改进以后可以记载shortest path的路径,使用数组path[N]
int bellmanFord(int n[][N], int start, int dest) {
int dist[N];
int path[N];
int i, j, k;
for(i = 0; i < N; i++) {
dist[i] = -1;
}
dist[dest] = 0;
for(i = 0; i < N - 1; i++) {
for(j = 0; j < N; j++) {
//graph is adjacent matrix, take O(n) time to find the min edge?
int minEdge = 0x0FFFFFFF;
int edgeTail;
for(k = 0; k < N; k++) {
if(graph[j][k] != -1) {
if(minEdge > graph[j][k]) {
minEdge = graph[j][k];
edgeTail = k;
}
}
}
if(dist[j] > dist[j - 1] + minEdge) {
path[j] = edgeTail;
dist[j] = dist[j - 1] + minEdge;
}
}
}
//output the path
int pathPosition = start;
while(pathPosition != dest) {
cout<<pathPosition<<" -> ";
pathPosition = path[pathPosition];
}
cout<<dest<<endl;
return dist[start];
}