> For the complete documentation index, see [llms.txt](https://mnunknown.gitbook.io/algorithm-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mnunknown.gitbook.io/algorithm-notes/topological_sortff0c_tuo_pu_pai_xu/undirected_graph-_dfs.md).

# Undirected Graph, DFS

## [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)

### 无向图的 DFS 要注意避免 “原路返回” 的情况，仅仅依靠设 state = 1 是不行的，所以 dfs 里最好有个参数，代表 “前一个节点”，这样在下一步的搜索中可以直接跳过，又避免了误判有环。

```java
public class Solution {
    public boolean validTree(int n, int[][] edges) {
        int[] states = new int[n];
        ArrayList[] graph = new ArrayList[n];

        for(int i = 0; i < n; i++){
            graph[i] = new ArrayList();
        }

        for(int[] edge : edges){
            graph[edge[0]].add(edge[1]);
            graph[edge[1]].add(edge[0]);
        }

        if(hasCycle(-1, 0, states, graph)) return false;

        for(int state : states){
            if(state == 0) return false;
        }

        return true;
    }

    private boolean hasCycle(int prev, int cur, int[] states, ArrayList[] graph){
        states[cur] = 1;
        boolean hasCycle = false;

        for(int i = 0; i < graph[cur].size(); i++){
            int next = (int) graph[cur].get(i);
            if(next != prev){
                if(states[next] == 1) return true;
                else if(states[next] == 0){
                    hasCycle = hasCycle || hasCycle(cur, next, states, graph);
                }
            }

        }

        states[cur] = 2;
        return hasCycle; 
    }
}
```


---

# 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://mnunknown.gitbook.io/algorithm-notes/topological_sortff0c_tuo_pu_pai_xu/undirected_graph-_dfs.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.
