假设条件同上。。
整个算法最核心的,个人觉得就是一个公式:
weight[a][b] = min{weight[a][b], weight[a][c]+weight[c][b]}
即,从一点到另外一点的最短距离,是在直线和经过一个中间点的‘绕路’距离之间求最短。。然后利用上一次的结果迭代。。
/* * author: buer * github: buer0.github.com */ #include <stdio.h> #include <stdlib.h> #define MAXSIZE 10 typedef struct Graph { int table[MAXSIZE][MAXSIZE]; int num; }Graph; void createTable(Graph *graph); void printTable(Graph *graph); void shortest(Graph *graph); int main(int argc, char *argv[]) { Graph graph; createTable(&graph); printTable(&graph); shortest(&graph); return 0; } void shortest(Graph *graph) { int num = graph->num; int pre[num][num]; int weight[num][num]; int i, j, k; for(i=0; i<num; i++) { for(j=0; j<num; j++) { pre[i][j] = j; weight[i][j] = (graph->table)[i][j]; } } for(i=0; i<num; i++) { for(j=0; j<num; j++) { for(k=0; k<num; k++) { if( weight[i][k] > weight[i][j] + weight[j][k] ) { weight[i][k] = weight[i][j] + weight[j][k]; pre[i][k] = j; } } } } printf("result:\n"); for(i=0; i<num; i++) { for(j=0; j<num; j++) { printf("%d ", weight[i][j]); } printf("\n"); } } void createTable(Graph *graph) { int i, j, temp; printf("输入节点数:"); scanf("%d", &(graph->num)); for(i=0; i<graph->num; i++) { printf("第 %d 行:", i+1); for(j=0; j<graph->num; j++) { scanf("%d", &temp); if(temp == ‘ ‘) { j --; }else { (graph->table)[i][j] = temp; } } getchar(); } } void printTable(Graph *graph) { int i,j; printf("\n"); for(i=0; i<graph->num; i++) { for(j=0; j<graph->num; j++) { printf("%d ", (graph->table)[i][j]); } printf("\n"); } }
时间: 2024-10-24 22:40:25