Floyd最短路

来源:互联网 发布:唯一有毒哺乳动物知乎 编辑:程序博客网 时间:2024/05/18 00:14


用邻接矩阵实现floyd找最短路算法

测试所用图如下:


#include<string.h>#include<string>#include<algorithm>#include<cmath>#include<stdio.h>#include<iostream>#include<set>#define inf 65535using namespace std;struct Graph//用邻接矩阵来保存图{int arc[100][100];int vertex[100];int num_ver,num_edge;};typedef int PathMatirx[100][100];//用来记录路径typedef int ShortPathTable[100][100];//用来记录各点到各点的最短距离void create(Graph *g)//建立邻接矩阵{scanf("%d%d",&g->num_ver,&g->num_edge);int i,j,y,x,z;for(i=0;i<g->num_ver;i++)//输入顶点scanf("%d",&g->vertex[i]);for(i=0;i<g->num_ver;i++)//邻接矩阵初始化    {    for(j=0;j<g->num_ver;j++)    {        if(i==j)g->arc[i][j]=0;        else g->arc[i][j]=inf;    }}for(i=0;i<g->num_edge;i++)//输入边的信息{    scanf("%d%d%d",&x,&y,&z);    g->arc[x][y]=z;    g->arc[y][x]=z;}}void shortpath(Graph *g,PathMatirx *p,ShortPathTable *d){//求最短路及其路径int v,w,k;for(v=0;v<g->num_ver;v++){    for(w=0;w<g->num_ver;w++){        (*d)[v][w]=g->arc[v][w];        (*p)[v][w]=w;    }}for(k=0;k<g->num_ver;k++){    for(v=0;v<g->num_ver;v++)    {        for(w=0;w<g->num_ver;w++)        {           if((*d)[v][w]>(*d)[v][k]+(*d)[k][w]){            (*d)[v][w]=(*d)[v][k]+(*d)[k][w];            (*p)[v][w]=(*p)[v][k];           }        }    }}//以下一段是测试用for(int i=0;i<g->num_ver;i++){    for(int j=0;j<g->num_ver;j++)        printf("%5d ",(*d)[i][j]);    printf("\n");}}void ShowPath(Graph *g,PathMatirx *p,ShortPathTable *d,int x,int y){int v,w,tmp;for(w=0;w<g->num_ver;w++)printf("*%d ",(*d)[x][w]);//打印起始点到各点的最短距离printf("\n");printf("%d",x);//打印起点v=(*p)[x][y];while(v!=y){    printf("->%d",v);    v=(*p)[v][y];}printf("->%d\n",y);//打印终点}int main(){int i,j,k;Graph G;create(&G);ShortPathTable d;PathMatirx p;shortpath(&G,&p,&d);/*for(i=0;i<G.num_ver;i++){    for(j=0;j<G.num_ver;j++)        printf("%d ",d[i][j]);    printf("\n");}for(i=0;i<G.num_ver;i++){    for(j=0;j<G.num_ver;j++)        printf("%d ",p[i][j]);    printf("\n");}ShowPath(&G,&p,&d,1,7);return 0;}/*9 160 1 2 3 4 5 6 7 80 1 10 2 51 3 71 4 51 2 32 4 12 5 73 6 33 4 24 6 64 7 94 5 35 7 56 8 76 7 27 8 4*/

ShortPathTable矩阵里[v][w]代表v到w的最短距离

在PathMatirx矩阵里找v到x路径时,就打印相应的那一列,比如说0->8,则从0

开始按索引打印到8.


(图来自<<大话数据>>一书)



测试结果如下图:


原创粉丝点击