#include<iostream>
using namespace std;
typedef char VertexType;
typedef int EdgeType;
const int MAXVEX = 100;
const int INFINITY = 65535;
typedef int Pathmatirx[MAXVEX][MAXVEX];
typedef int ShortPathTable[MAXVEX][MAXVEX];
typedef struct
{
VertexType vexs[MAXVEX];
EdgeType arc[MAXVEX][MAXVEX];
int numVertexes,numEdges;
}MGraph;
/*
建立无向网图的邻接矩阵表示
*/
void CreateMGraph_Undirected(MGraph *G)
{
int i,j,k,w;
cout<<"请输入顶点数和边数:"<<endl;
cin>>G->numVertexes>>G->numEdges;
cout<<"请输入顶点名称:"<<endl;
for(i = 0;i < G->numVertexes;++i)//输入顶点
{
cin>>G->vexs[i];
}
for(i = 0;i < G->numVertexes;++i)//初始化邻接矩阵,除对角线元素 = 0,其余为INFINITY;
{
for(j = 0;j < G->numVertexes;++j)
{
if(i == j)
{
G->arc[i][j] = 0;
}
else
{
G->arc[i][j] = INFINITY;
}
}
}
for(k = 0;k < G->numEdges;++k)//完成邻接矩阵的填写工作
{
printf("请输入边(vi,vj)上的下标i,下标j和权w:\n");
cin>>i>>j>>w;
G->arc[i][j] = G->arc[j][i] = w;
}
}
void ShowMGraph(MGraph *G)//打印图的信息
{
cout<<"图的顶点,边数为:"<<G->numVertexes<<","<<G->numEdges<<endl;
cout<<"邻接矩阵为:"<<endl;
for(int i = 0;i < G->numVertexes;++i)
{
for(int j = 0;j < G->numVertexes;++j)
{
if(G->arc[i][j] == INFINITY)
{
cout<<"# ";
}
else
{
cout<<" "<<G->arc[i][j]<<" ";
}
}
cout<<endl;
}
}
//Floyd算法,求网图G中各顶点到V到其余顶点w最短路径,P[v][w]以及带权长度D[v][w]
void ShortestPath_Floyd(MGraph *G,Pathmatirx * P,ShortPathTable * D)
{
int v,w,k;
for(v = 0;v < G->numVertexes;++v)
{
for(w = 0;w < G->numVertexes;++w)
{
(*D)[v][w] = G->arc[v][w];
(*P)[v][w] = w;
}
}
for(k = 0;k < G->numVertexes;++k)
{
for(v = 0;v < G->numVertexes;++v)
{
for(w = 0;w < G->numVertexes;++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];
}
}
}
}
}
最短路径——Floyd算法
最新推荐文章于 2024-08-26 13:11:27 发布