最短経路の距離行列から経路行列を構築するアルゴリズム
全点対最短経路問題(All-Pairs Shortest Paths Problem)において、Floyd-Warshall法などで最短経路の距離行列が求められている場合に、その最短距離行列から対応する経路行列を構築するアルゴリズムについてのメモ。アルゴリズムはO(n^3)のアルゴリズムで単純な実装ではFloyd-Warshall法と同程度の計算処理時間がかかる。以下はCによる実装例。
void construct_aps_path(const int n, const int **A, const int **D, int **P) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { if (D[i][j] == D[i][k]+A[k][j]) { P[i*n+j] = k; break; } if (k != n-1) { P[i*n+j] = NIL; } } } } }
nが問題サイズ、Aが入力距離行列、Dが最短経路の距離行列、Pは求める最短経路のpredecessor行列。初期条件等はCLRSの"Introduction to Algorithms"の"Constructing a shortest path"の項を参照(この問題はCLRSの演習問題にもなっている)。入力グラフによっては、Floyd-Warshall法の計算途上で経路行列も記録させた場合と結果が違うものになることもある。