1. 程式人生 > >最短路徑(弗洛伊德算法)

最短路徑(弗洛伊德算法)

creat github lib tab auth logs sca for maxsize

假設條件同上。。

整個算法最核心的,個人覺得就是一個公式:

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"); } }

最短路徑(弗洛伊德算法)