> For the complete documentation index, see [llms.txt](https://garychang.gitbook.io/data-structure/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://garychang.gitbook.io/data-structure/4-graph/4.4-shortest-path-length/4.4.3-floyd-warshall-algorithm.md).

# 4.4.3 - Floyd-Warshall algorithm

* 可有負邊存在

### 1. 演算法

$$A^k$$為一個n\*n矩陣， $$A^{k}\[i.j]$$為 $$i$$ 到 $$j$$ 的shortest path length，**途中**經過的頂點編號必須≤$$k$$。

$$A^0$$為Cost Matrix，依序求出 $$A^1, A^2,...,A^n$$， $$A^n$$及為所求。

<img src="https://2769815795-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGckN3OAfinKuVIrkMj%2F-LJ2z79bSccARCkiAQph%2F-LJ3-i7vbi4VhzYzZzNE%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-08-04%2016.16.39.jpg?alt=media&amp;token=2fb4f8d3-3656-4aea-8b31-29cd59a7827e" alt="" data-size="original">&#x20;

e.g.

<img src="https://2769815795-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGckN3OAfinKuVIrkMj%2F-LJ30Hm7hYZzskSCni65%2F-LJ31MURREKtbNqMO9oP%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-08-04%2016.23.59.jpg?alt=media&amp;token=449eff93-6ef6-4f83-a018-f667e363e037" alt="" data-size="original">&#x20;

$$A^0= \begin{bmatrix} 0&4&11\ 6&0&2\ 3&∞&0 \end{bmatrix}$$&#x20;

&#x20;$$A^1= \begin{bmatrix} 0&4&11\ 6&0&2\ 3&7&0 \end{bmatrix}$$&#x20;

$$A^2= \begin{bmatrix} 0&4&6\ 6&0&2\ 3&7&0 \end{bmatrix}$$&#x20;

$$A^3= \begin{bmatrix} 0&4&6\ 5&0&2\ 3&7&0 \end{bmatrix}$$&#x20;
