#include<bits/stdc++.h>
#define MaxInt 1e8
#define MVNum 100
#define OK 1
#define ERROR 0
using namespace std;
typedef int VerTexType;
typedef int Status;
typedef int ArcType;
bool visit[MVNum];
int Path[MVNum][MVNum];
int D[MVNum][MVNum];
typedef struct
{
VerTexType vex[MVNum];
ArcType arcs[MVNum][MVNum];
int vexnum,arcnum;
}AMGraph;
int LocateVex(AMGraph &G,VerTexType &v)
{
int i;
for (i=1;i<=G.vexnum;i++)
{
if (G.vex[i]==v)
return i;
}
if (i>=G.vexnum) return ERROR;
else return 0;
}
Status CreateUDN(AMGraph &G)
{
int i,j,k,w;
VerTexType v1,v2;
printf("输入图的顶点数:");
scanf("%d",&G.vexnum);
printf("输入边的条数:");
scanf("%d",&G.arcnum);
for (i=1;i<=G.vexnum;i++)
G.vex[i] = i;
for (i=1;i<=G.vexnum;i++)
for (j=1;j<=G.vexnum;j++)
G.arcs[i][j] = MaxInt;
printf("\n输入各边的起点与终点以及权值:\n");
for (k=1;k<=G.arcnum;k++)
{
cin>>v1>>v2>>w;
i = LocateVex(G,v1);
j = LocateVex(G,v2);
G.arcs[i][j] = w;
}
printf("\n图创建成功!\n");
return OK;
}
void Travel(AMGraph G)
{
int i,j;
printf("创建的邻接矩阵如下:\n\n");
for (i=1;i<=G.vexnum;i++)
{
for (j=1;j<=G.vexnum;j++)
printf("%d ",G.arcs[i][j]);
printf("\n");
}
puts("");
}
void ShortestPath_Floyd(AMGraph G)
{
int i,j,k;
for (i=1;i<=G.vexnum;i++)
for (j=1;j<=G.vexnum;j++)
{
D[i][j] = G.arcs[i][j];
if (D[i][j]<MaxInt && i!=j)
Path[i][j] = i;
else Path[i][j] = -1;
}
for(k=1;k<=G.vexnum;k++)
for(i=1;i<=G.vexnum;i++)
for(j=1;j<=G.vexnum;j++)
if(D[i][k]+D[k][j]<D[i][j])
{
D[i][j] = D[i][k] + D[k][j];
Path[i][j] = Path[k][j];
}
}
void Path_Length(AMGraph G)
{
int vs,ve,x,temp;
printf("输入要求路径的起点与终点:");
scanf("%d %d",&vs,&ve);
printf("\n");
printf("最短路径长为:");
printf("%d\n",D[vs][ve]);
stack<int> sta;
sta.push(ve);
x = ve;
while (Path[vs][x]!=vs)
{
sta.push(Path[vs][x]);
x = Path[vs][x];
}
sta.push(vs);
printf("最短路径为: ");
temp = sta.top();
sta.pop();
printf("%d",temp);
while (!sta.empty())
{
temp = sta.top();
sta.pop();
printf("->%d",temp);
}
puts("");
}
int main()
{
//freopen("in.txt","r",stdin);
AMGraph G;
CreateUDN(G);
Travel(G);
ShortestPath_Floyd(G);
Path_Length(G);
return 0;
}
最短路径(邻接矩阵)(弗洛伊德算法)
猜你喜欢
转载自blog.csdn.net/qq_40912854/article/details/84035011
今日推荐
周排行