最短路徑(鄰接矩陣)(弗洛伊德演算法)
阿新 • • 發佈:2018-11-27
#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; }