> For the complete documentation index, see [llms.txt](https://jaywin.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jaywin.gitbook.io/leetcode/topics/dfs-bfs.md).

# DFS BFS

## Key points:

* DFS-stack\&recursion, BFS-queue
* If BFS works, never use DFS because of StackOverflow, important! like this one: [surrounded-regions](https://leetcode.com/problems/surrounded-regions/)
* DFS:
  * A and B is connected?
  * Connected component. (Union Find is faster because no need to build graph)
  * Search path
  * Has cycle
  * two color
  * Backtracking, all results
* BFS:
  * shortest path
  * connected component
  * topological sorting
  * level order traversal
  * Topological sorting
* Need to mark visited element:
  * if you need to get value, use `HashMap`
  * if just determine contain or not, use `HashSet` or `boolean[]`

![](https://kevhuang.com/content/images/2015/06/tree-traversal.gif)

## Templates

### BFS in a tree

* Queue -> q.offer(root) -> while -> levelNum = q.size() -> for loop
* if you don't need layer, `for loop` is not required.

```java
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Queue<TreeNode> q = new Queue<TreeNode>();

        if (root == null) return res;

        q.offer(root);
        while (!q.isEmpty()) {
            int levelNum = q.size();
            List<Integer> tmpList = new ArrayList<Integer>();
            for (int i = 0; i < levelNum; i++) {
                TreeNode curr = q.poll();
                tmpList.add(curr.val);
                if (curr.left != null) q.offer(curr.left);
                if (curr.right != null) q.offer(curr.right);
            }
            res.add(tmpList);
        }
        return res;
    }
}
```

### Permutation & Combination

![](https://pic3.zhimg.com/50/52a7a08bcfb9d133a8683ec26aa1924a_hd.jpg) ![](https://pic1.zhimg.com/50/8c70313549374daf4db1b8b436267f50_hd.jpg)


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://jaywin.gitbook.io/leetcode/topics/dfs-bfs.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
