無向DFS遍歷

無向圖的 DFS 要注意避免 “原路返回” 的情況

(1)僅僅依靠設 state = 1 是不行的,所以 dfs 裏最好有個參數,代表 “前一個節點”,這樣在下一步的搜索中可以直接跳過,又避免了誤判有環。

(2)對於起點0,他的pre是-1
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; 
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章