Floyd最短路徑算法是基於這樣一個事實:從到的最短路徑總是先從沿着一條路到某一點,再沿到。而從到這條路必然是從到的最短路。
下面我們來進行具體的代碼設計,算法設計的基本思想是:首先設置一個長度矩陣,然後
第一次迭代:從一點到另一點只能通過,求任意兩點間的最短路徑,更新長度矩陣。
第二次迭代:從一點到另一點只能通過點,求任意兩點間的最短路徑,更新長度矩陣。
第三次迭代:從一點到另一點只能通過,求任意兩點間的最短路徑,更新長度矩陣。
…
經過N(N就是矩陣的長度或者寬度)次迭代,我們便可以得到最終的長度矩陣,這個長度矩陣便可以反映各個點之間的最短距離。
void Floyd(int (*Map)[7], int (*result)[7], int row, int column)
{
//This part is to keep the Map, because i don't want it to be changed, i copy it to the result map.
int k, i, j;
for(i = 0; i < row; i++){
for(j = 0; j < column; j++){
result[i][j] = Map[i][j];
}
}
//This is the hardcore of the Floyd algorithm
for(k = 0;k < row;k++)
for(i = 0;i < row;i++)
for(j = 0;j < column;j++)
if( result[i][j] > result[i][k] + result[k][j] )
result[i][j] = result[i][k] + result[k][j];
}