Grafalgo
Library of useful data structures and algorithms
|
00001 #include "stdinc.h" 00002 #include "Wdigraph.h" 00003 00004 using namespace grafalgo; 00005 00006 void floyd(Wdigraph& dig, int* dist[], vertex* mid[]) { 00007 // Compute a solution to the all pairs shortest path problem 00008 // using Floyd's algorithm. Return dist[u][v]=distance from u to v 00009 // and mid[u][v]=an intermediate mid-point of the shortest u-v path. 00010 00011 vertex u,v,w; edge e; 00012 00013 // Initialize dist and mid. 00014 for (u = 1; u <= dig.n(); u++) { 00015 for (v = 1; v <= dig.n(); v++) { 00016 if (u == v) dist[u][v] = 0; 00017 else dist[u][v] = Util::BIGINT32; 00018 mid[u][v] = 0; 00019 } 00020 } 00021 for (u = 1; u <= dig.n(); u++) { 00022 for (e = dig.firstOut(u); e != 0; e = dig.nextOut(u,e)) { 00023 v = dig.head(e); 00024 dist[u][v] = dig.length(e); 00025 } 00026 } 00027 00028 // Compute distances. 00029 for (v = 1; v <= dig.n(); v++) { 00030 if (dist[v][v] < 0) Util::fatal("floyd: negative cycle"); 00031 for (u = 1; u <= dig.n(); u++) { 00032 for (w = 1; w <= dig.n(); w++) { 00033 if (dist[u][v] != Util::BIGINT32 && 00034 dist[v][w] != Util::BIGINT32 00035 && dist[u][w] > dist[u][v] + dist[v][w]) { 00036 dist[u][w] = dist[u][v] + dist[v][w]; 00037 mid[u][w] = v; 00038 } 00039 } 00040 } 00041 } 00042 }