只有五行的Floyd最短路径算法

来源:互联网 发布:js获取表单的值 编辑:程序博客网 时间:2024/06/10 07:32

参考: http://ahalei.blog.51cto.com/4767671/1383613

本算法是罗伯特·弗洛伊德Robert W Floyd  1962年发表的寻找最短路径算法,该算法的实现思想是动态规划,通过局部最优解,推导出全局最优解。

#include<stdio.h>#include<stdlib.h>void main(){int i,j,k;int inf=99999999;int vertex_num,edge_num,dist,array[20][20];printf("Please input the num of vertex and edge:\n");scanf("%d %d",&vertex_num,&edge_num);//init road mapfor(i=0;i<vertex_num;i++){for(j=0;j<vertex_num;j++){if(i==j)array[i][j]=0;elsearray[i][j]=inf;}}//init edgeprintf("Please input the vertex i,j,distance for edge:\n");for(k=0;k<edge_num;k++){scanf("%d %d %d",&i,&j,&dist);if(i>vertex_num || j>vertex_num || i<=0 || j<=0){printf("the range of i and j is 1~%d\n",vertex_num);k--;continue;}array[i-1][j-1]=dist;}//floyd algrithmfor(k=0;k<vertex_num;k++)for(i=0;i<vertex_num;i++)for(j=0;j<vertex_num;j++)if(array[i][j]>(array[i][k]+array[k][j]))array[i][j]=array[i][k]+array[k][j];//output resultprintf("\n***************************\n");printf("the result shortest map is:\n");for(i=0;i<vertex_num;i++){for(j=0;j<vertex_num;j++){if(array[i][j]==inf){printf("  inf ");}else{printf("%5d ",array[i][j]);}}printf("\n");}}



运算结果

norton@norton-laptop:~/learning/sample code/algrithm/dynamic_programing/floyd$ ./floyd.o
Please input the num of vertex and edge:
4 8
Please input the vertex i,j,distance for edge:
1 2 10
1 3 20
1 4 30
2 1 15
2 3 25
3 4 35
2 4 33
4 2 22

***************************
the result shortest map is:
    0    10    20    30
   15     0    25    33
   72    57     0    35
   37    22    47     0

该算法不能算负权回路,即dist是负数。概算法也没把经过的点列出来,可以根据实际情况扩增。

0 0
原创粉丝点击