> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/graph-theory/shortest-path.md).

# 最短路径

最短路径是图论核心问题：求两点间边权和最小的路径。

### Floyd：多源最短路

求**任意两点**间最短路，复杂度 **O(n³)**，适合 n ≤ 500，可处理负权（无负环）。

```cpp
int d[N][N];
// 初始化：d[i][i]=0，有边 d[u][v]=w，无边为 INF
for (int k = 1; k <= n; k++)
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
```

### Dijkstra：单源最短路（非负权）

用优先队列优化，复杂度 **O(m log n)**。不能处理负权边。

```cpp
vector<pair<int,int>> adj[N];   // (邻点, 权)
int dist[N];
void dijkstra(int s) {
    fill(dist, dist + N, 1e9);
    priority_queue<pair<int,int>, vector<pair<int,int>>, greater<>> pq;
    dist[s] = 0; pq.push({0, s});
    while (!pq.empty()) {
        auto [d, u] = pq.top(); pq.pop();
        if (d > dist[u]) continue;
        for (auto [v, w] : adj[u])
            if (dist[u] + w < dist[v]) {
                dist[v] = dist[u] + w;
                pq.push({dist[v], v});
            }
    }
}
```

### Bellman-Ford / SPFA

可处理**负权边**，并判断负环。SPFA 是 Bellman-Ford 的队列优化，最坏 O(nm)。

### 对比

| 算法           | 适用     | 复杂度           |
| ------------ | ------ | ------------- |
| Floyd        | 多源、负权  | O(n³)         |
| Dijkstra     | 单源、非负权 | O(m log n)    |
| Bellman-Ford | 单源、负权  | O(nm)         |
| SPFA         | 单源、负权  | 平均较快，最坏 O(nm) |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/graph-theory/shortest-path.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
