> 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/graph-traversal.md).

# 图的遍历与连通块

### 图的 DFS

```cpp
vector<int> adj[N];
bool vis[N];

void dfs(int u) {
    vis[u] = true;
    cout << u << " ";
    for (int v : adj[u])
        if (!vis[v]) dfs(v);
}
```

### 图的 BFS

```cpp
void bfs(int s) {
    queue<int> q;
    q.push(s); vis[s] = true;
    while (!q.empty()) {
        int u = q.front(); q.pop();
        cout << u << " ";
        for (int v : adj[u])
            if (!vis[v]) { vis[v] = true; q.push(v); }
    }
}
```

### 连通块（泛洪 floodfill）

遍历所有顶点，未访问的即为一个新连通块：

```cpp
int components = 0;
for (int i = 1; i <= n; i++)
    if (!vis[i]) { dfs(i); components++; }
cout << components;
```

### 复杂度

邻接表下 DFS/BFS 均为 **O(n + m)**；邻接矩阵为 O(n²)。

### 应用

* 判断连通性 / 求连通块个数
* 迷宫、岛屿数量（二维网格 floodfill）
* 二分图判定（染色）


---

# 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/graph-traversal.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.
