/* Dijkstra algorithm can only calculate the lowest cost from one root vertex to others. The time-complexity is n*n. * For vertex-to-vertex lowest cost calculating, you can use Dijkstra for n times. But the codes looks complex. * The time-complexity is n*n*n. * Floyd algorithm takes us the concise code.The time-complexity is the same to Dijkstra. The following codes * show you the realization of algorithm Floyd. * version: 0.1; by: double; date: 2009-07-12 */ #include "/usr/c/head.h" #define MAX 20 #define INT_MAX ((int)(~0U>>1)) #define SCAN_INT(x, y); if (scanf("%d", &x) != EOF) while ((y = getchar()) != '/n' && y != EOF) {;} #define SCAN_CHAR(x, y); if (scanf("%c", &x) != EOF) while ((y = getchar()) != '/n' && y != EOF) {;} typedef int arc_type; typedef char vex_type; typedef struct matrix_graph { vex_type vexs[MAX]; arc_type arcs[MAX][MAX]; int vexnum, arcnum; }matrix_graph; matrix_graph G; int path[MAX][MAX][MAX]; int distance[MAX][MAX]; int locate_vex(matrix_graph G, vex_type v) { int i; for (i = 0; i < G.vexnum; ++i) if (G.vexs[i] == v) return i; return -1; } status init_graph(matrix_graph *G) { int temp, i, j, p1, p2; vex_type v1, v2; printf("Input the vexnum:"); SCAN_INT(G->vexnum, temp); for (i = 0; i < G->vexnum; ++i) { printf("No.%d:", i + 1); SCAN_CHAR(G->vexs[i], temp); for (j = 0; j < G->vexnum; ++j) G->arcs[i][j] = INT_MAX; } printf("Input the arcnum:"); SCAN_INT(G->arcnum, temp); for (i = 0; i < G->arcnum; ++i) { printf("No.%d, v1:", i + 1); SCAN_CHAR(v1, temp); printf("No.%d, v2:", i + 1); SCAN_CHAR(v2, temp); p1 = locate_vex(*G, v1); if (p1 == -1) { printf("v1 = %c out of range!/n", v1); exit(ERROR); } p2 = locate_vex(*G, v2); if (p2 == -1) { printf("v2 = %c out of range!/n", v2); exit(ERROR); } printf("Weight:"); SCAN_INT(G->arcs[p1][p2], temp); } return OK; } status print_graph(void) { int i, j; printf("vertexs are:/n"); for (i = 0; i < G.vexnum; ++i) printf("%c/t", G.vexs[i]); printf("/n"); printf("arcs are:/n"); for (i = 0; i < G.vexnum; ++i) { for (j = 0; j < G.vexnum; ++j) printf("%d/t", G.arcs[i][j]); printf("/n"); } return OK; } status floyd(void) { int u, v, w, i; for (v = 0; v < G.vexnum; ++v) for (w = 0; w < G.vexnum; ++w) { distance[v][w] = G.arcs[v][w]; for (u = 0; u < G.vexnum; ++u) path[v][w][u] = FALSE; if (distance[v][w] < INT_MAX) path[v][w][v] = path[v][w][w] = TRUE; } for (u = 0; u < G.vexnum; ++u) for (v = 0; v < G.vexnum; ++v) for (w = 0; w < G.vexnum; ++w) if (distance[v][u] + distance[u][w] > 0 && distance[v][u] + distance[u][w] < distance[v][w]) { distance[v][w] = distance[v][u] + distance[u][w]; for (i = 0; i < G.vexnum; ++i) path[v][w][i] = path[v][u][i] || path[u][w][i]; } return OK; } int main(void) { int i, j; init_graph(&G); printf("Graph initilized OK!/n"); print_graph(); floyd(); printf("Distance are:/n"); for (i = 0; i < G.vexnum; ++i) { for (j = 0; j < G.vexnum; ++j) printf("%d/t", distance[i][j] != INT_MAX ? distance[i][j] : -1); printf("/n/n/n"); } printf("/n"); return 0; }