> 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/search/dfs.md).

# 深度优先搜索

### 搜索思想

深度优先搜索（DFS）沿着一条路径走到底，走不通再**回溯**到上一个分叉点，尝试其它路径。可用递归或栈实现。

### 回溯的本质

“前进 → 标记 → 探索 → 撤销标记 → 返回”。撤销标记就是回溯的关键。

### 网格 DFS 模板

```cpp
int n, m, ans;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
bool vis[105][105];

void dfs(int x, int y) {
    ans++;
    vis[x][y] = true;
    for (int k = 0; k < 4; k++) {
        int nx = x + dx[k], ny = y + dy[k];
        if (nx >= 0 && nx < n && ny >= 0 && ny < m
            && !vis[nx][ny]) {
            dfs(nx, ny);
        }
    }
}
```

### 求连通块数量

```cpp
int count = 0;
for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
        if (!vis[i][j]) { dfs(i, j); count++; }
```

### DFS vs BFS

|      | DFS           | BFS        |
| ---- | ------------- | ---------- |
| 数据结构 | 递归 / 栈        | 队列         |
| 特点   | 一条路走到底        | 逐层扩展       |
| 适合   | 遍历、连通性、回溯、全排列 | 无权最短路、最少步数 |

### 全排列（回溯 + 撤销标记）

```cpp
void perm(int k) {
    if (k == n) { /* 输出排列 */ return; }
    for (int i = 1; i <= n; i++) {
        if (!used[i]) {
            used[i] = true; ans[k] = i;
            perm(k + 1);
            used[i] = false;      // 回溯
        }
    }
}
```

### 剪枝

在搜索前判断“这条路不可能有解”就提前返回，能大幅提速（如越界、已访问、超过最优解）。


---

# 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/search/dfs.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.
