全文轉自:http://blog.csdn.net/perfect2011/article/details/7568375
Floyd算法
作者:silence、2012年5月15日
本文參考:Google,數據結構(C語言)
本人聲明:個人原創,轉載請註明出處。
本文鏈接:http://blog.csdn.net/perfect2011/article/details/7568375
一 簡介
三 代碼實現
- #include <cstdlib>
- #include <iostream>
- /*
- Author : silence
- Time : 2012/5/15
- description : 每一對頂點的最短距離
- */
- using namespace std;
- struct Graph
- {
- int arrArc[20][20];
- int verCount;
- int arcCount;
- };
- void floyd(Graph *p,int dis[20][20]){
- for(int k = 0;k<p->verCount;k++)
- for(int i = 0;i<p->verCount;i++)
- for(int j = 0;j<p->verCount;j++)
- {
- //存在更近的路徑,則更新
- if(dis[i][j]>dis[i][k]+dis[k][j])
- dis[i][j]=dis[i][k]+dis[k][j];
- }
- }
- int main(int argc, char *argv[])
- {
- Graph g;
- cout<<"input the number of ver and arc"<<endl;
- cin>>g.verCount>>g.arcCount;
- cout<<"input the arc"<<endl;
- //初始化鄰接矩陣
- for(int i = 0;i<g.verCount;i++)
- { for(int j = 0;j<g.verCount;j++)
- {
- //i到本身的距離爲0
- //不同節點值爲不可達
- if(i==j) g.arrArc[i][i]= 0;
- else
- g.arrArc[i][j] = 65535;
- }
- }
- int a,b,distance;
- //無向圖 輸入各邊的權值
- for(int i=0;i<g.arcCount;i++)
- {
- cin>>a>>b>>distance;
- g.arrArc[a][b]=g.arrArc[b][a]=distance;
- }
- floyd(&g,g.arrArc);
- cout<<g.arrArc[0][1]<<endl;
- system("PAUSE");
- return EXIT_SUCCESS;
- }
Floyd算法的基本思想如下:從任意節點A到任意節點B的最短路徑不外乎2種可能:
1是直接從A到B,
2是從A經過若干個節點X到B。
所以,我們假設dis(AB)爲節點A到節點B的最短路徑的距離,對於每一個節點X,我們檢查dis(AX) + dis(XB) < dis(AB)是否成立,如果成立,證明從A到X再到B的路徑比A直接到B的路徑短,我們便設置dis(AB)= dis(AX) +dis(XB),這樣一來,當我們遍歷完所有節點X,dis(AB)中記錄的便是A到B的最短路徑的距離。
五注意點
三個循環的求中間點的K的循環必須放在外面。
因爲如果放在內層,對於A—B之間的經過AX和BX的還沒有求到最小值,所以A—B最後不是最小值
六測試數據
Input:
4 4
0 1 11
1 2 2
2 3 3
3 0 4
Output :
9