圖論---最短路(記錄路徑)
阿新 • • 發佈:2019-02-17
設計任務
校園導遊諮詢
問題描述:
設計一個校園導遊程式,為來訪的客人提供各種資訊查詢服務。
基本要求:
⑴設計華東交通大學的校園平面圖,所含景點不少於10個。以圖 中頂點表示校內各景點。
⑵存放景點名稱、代號、簡介等資訊;以邊表示路徑,存放路徑長度等相關資訊。
⑶為來訪客人提供圖中任意景點相關資訊的查詢。
⑷為來訪客人提供圖中任意景點的問路查詢,即查詢任意兩個景點之間的一條最短的簡單路徑。
詳細設計思想
1、概要設計
演算法 設計:考慮到校園地點數的侷限性,此課題完全可以用floy
我選擇的是Dijkstra演算法,因為演算法執行速度要比floy演算法更高效,效能更好,其次就是使用前驅
或者後驅來記錄,實現一個路線記錄的效果..
//// Dijkstra演算法程式碼: #define inf 1000000000 const int maxx = 300; int temp; /// 地點的個數 int mark[maxx<<1]; /// 標記便於求最短路 int g[maxx][maxx]; /// 校園景點圖 int dist[maxx]; /// 單源最短路儲存 int pre[maxx]; /// 前驅記錄路徑 struct Node { string name; /// 景點地名 int num; /// 景點代號 string introduce; /// 景點介紹 }school[maxx]; void Dijkstra(int start,int end) /// 求最短路 { for(int i=1;i<=temp;i++) { dist[i]=g[start][i]; pre[i]=start; mark[i]=0; } dist[start]=0; mark[start]=1; pre[start]=-1; for(int i=1;i<=temp;i++) { int min=inf; int u=-1; for(int j=1;j<=temp;j++) { if(mark[j]==0 && dist[j]<min) { min=dist[j]; u=j; } } mark[u]=1; if(u<0) break; for(int j=1 ; j<=temp ; j++) { if(mark[j]==0 && dist[j]>dist[u]+g[u][j]) { dist[j]=dist[u]+g[u][j]; pre[j]=u; } } } if(dist[end] < inf) /// 判斷最短路是否存在? { cout<<"距離: "<<dist[end]<<endl; cout<<"路徑:"; int road[100],ss=0; road[ss++]=end; while(pre[end]!=start){ /// 記錄路徑 road[ss++]=pre[end]; end=pre[end]; } road[ss++]=start; cout<<school[road[ss-1]].name; for(int i=ss - 2 ; i>=0 ;i--) /// 列印路徑 { cout<<"--->"<<school[road[i]].name; } cout<<endl; } else cout<<"路徑不存在~"<<endl; cout<<"請按任意鍵返回!"; system("pause"); } //// Floy 演算法程式碼: #define inf 1000000000 const int maxx = 300; int temp; /// 地點的個數 int mark[maxx<<1]; /// 標記便於求最短路 int g[maxx][maxx]; /// 校園景點圖 int dist[maxx][maxx]; /// 單源最短路儲存 int pre[maxx][maxx]; /// 前驅記錄路徑 struct Node { string name; /// 景點地名 int num; /// 景點代號 string introduce; /// 景點介紹 }school[maxx]; void Floy(int start,int end) /// 求最短路 { for(int i=1;i<=temp;i++){ /// 初始化 for(int j=1;j<=temp;j++){ dist[i][j]=g[i][j]; } } int n=temp; for(int k=1; k<=n; k++) for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) if(dist[i][j] > dist[i][k]+dist[k][j]){ dist[i][j]=dist[i][k]+dist[k][j]; //// 更新路徑 pre[i][j] = pre[i][k]; //// 記錄路徑 } if(dist[start][end]==inf) cout<<"路徑不存在~"<<endl; else { cout<<"最短路:"<<dist[start][end]<<endl; cout<<"列印路徑: \n"<<start; while(start!=end){ /// 列印路徑 cout<<"-->"<<pre[start][end]; start=pre[start][end]; } } cout<<"請按任意鍵返回!"; system("pause"); } 演算法效能分析: Dijkstra 演算法時間複雜度為N的平方,Floy 時間複雜度為N的三次方 ,其中N為問題的規模
floy 演算法神牛部落格:
http://www.cnblogs.com/twjcnblog/archive/2011/09/07/2170306.html