本文へスキップ

リソース · ガイド・記事

Floyd–Warshall Algorithm

全点対間の最短経路を求めるFloyd-Warshallを説明しています。負閉路がない限り、負の辺の重みも扱えます。距離の表を使うので、グラフ上の動的計画法を学ぶ候補者に向いています。

確認日

元のサイトを開く: Floyd–Warshall Algorithm (元のサイトを新しいタブで開きます)

このトピックを練習グラフ の問題で練習用面接官を開きます。

ロードマップに追加

取り組んでいるロードマップにこのリソースを追加できます。自分用の追加リソースとして表示され、ロードマップの手順は変わらず、記録した手順数にも数えられません。

出典コンテンツの言語:英語

In computer science, the Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights (but with no negative cycles). A single execution of the algorithm will find the lengths (summed weights) of shortest paths between all pairs of vertices. Although it does not return details of the paths themselves, it is possible to reconstruct the paths with simple modifications to the algorithm. The Floyd–Warshall algorithm compares all possible paths through the graph between each pair of vertices. It is able to do this with O(|V|^3) comparisons in a graph. This is remarkable considering that there may be up to |V|^2 edges in the graph, and every combination of edges is tested. It does so by incrementally improving an estimate on the shortest path between two vertices, until the estimate is optimal. Consider a graph G with vertices V numbered 1 through N. Further consider a function shortestPath(i, j, k) that returns the shortest possible path from i to j using vertices only from the set {1, 2, ..., k} as intermediate points along the way. Now, given this function, our goal is to find the shortest path from each i to each j…

PrepKit の概要

この概要は PrepKit 編集部がソースリポジトリをもとに執筆・確認したもので、リソース本文の引用ではありません。

対象
ソースにレベルの記載はありません
形式
記事

扱っている内容

  • 部分問題shortestPath(i, j, k)。中継点として頂点1からkだけを使う、iからjへの最良の経路
  • 計算量をO(|V|^3)回の比較と記載
  • 負の重みを含む4頂点の例で、kが0から4までの各段階の距離行列を掲載
  • アルゴリズムが返すのは経路の長さだけで、経路自体を復元するには少し手を加える必要があるという注記

使い方

PrepKit の学習アドバイスであり、ソースの主張ではありません。

例からk = 0の行列を作り直し、以降の表を自分で計算してからREADMEと比べてください。次に三重ループを書き、次の中継先を記録する行列を加えて、任意の2頂点間の実際の経路を出力できるようにします。

範囲と制約

漸化式自体はWikipediaから描画された画像としてしか載っていないため、読みにくかったり書き写しにくかったりする可能性があります。負閉路の検出と経路の復元は触れられているだけで、示されていません。k = 1の表では一つのセルがダッシュだけで表示されています。

利用方法と形式

MITライセンスのtrekhleb/javascript-algorithmsリポジトリ内のGitHub上のREADMEで、英語で無料で読めます。

PrepKit が 2026/10/02 に確認しました。 リソースの出典のコミット: 85293e3e2b88

この概要の根拠
  • src/algorithms/graph/floyd-warshall/README.md

この項目を掲載しているページ

PrepKit ニュースレターを受け取る

任意です。PrepKit の利用には必要ありません。

メールアドレスの取り扱いについて