> 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.1-dijkstras-algorithm.md).

# 4.4.1 - Dijkstra's algorithm

* 不可有負邊存在

### 1. 演算法

Cost Matrix `C[i][j]`:為一個nxn矩陣，n=|V|

$$C\[i,j]= \begin{cases} 邊長, & \textrm{if (i, j) exists}\ ∞, & \textrm{if (i, j) doesn't exist}\ 0, & \textrm{if i = j} \end{cases}$$&#x20;

$$S\[i]= \begin{cases} 0, & \textrm{未確定起點到i的shortest path length}\ 1, & \textrm{已確定起點到i的shortest path length} \end{cases}$$&#x20;

$$Dist\[i]:\textrm{起點到i的shortest path length}$$&#x20;

<img src="/files/-LIulmljHpb97Ugj5QuE" alt="" data-size="original">&#x20;

$$Dist\[w]=min{Dist\[w],\ Dist\[u]+C\[u,w]}$$&#x20;

### 2. 範例

&#x20;<img src="/files/-LJ2lqUDIwUpQLci3tOM" alt="" data-size="original">&#x20;

求5到各點的最短路徑？

![](/files/-LJ2mRFmxqsxTVsspEZC)
