Undirected Graph, DFS

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

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; 
    }
}

Last updated