无向图如何检测Cycle?

无向图的DFS做法判断环是否存在只用在有向图的基础上加个prev即可。因为无相图的A-B如果没有prev可能被误判断为有环。只有当next!=prev的时候我才遍历。

如何正确 detect cycle?

  • 用 int[] 表示每个点的状态,其中

    • 0 代表“未访问”;

    • 1 代表“访问中”;

    • 2 代表“已访问”;

  • 如果在循环的任何时刻,我们试图访问一个状态为 “1” 的节点,都可以说明图中有环。

    • 如何正确识别图中 connected components 的数量?

      • 添加任意点,探索所有能到达的点,探索完毕数量 +1;

      • 如此往复,直到已探索点的数量 = # of V in graph 为止。

    BFS 做法,时间复杂度 O(E + V);

Graph Valid Tree

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

        Queue<Integer> queue = new LinkedList<>();

        queue.offer(0); 
        states[0] = 1;
        int count = 0;

        while(!queue.isEmpty()){
            int node = queue.poll();
            count ++;
            for(int i = 0; i < graph[node].size(); i++){
                int next = (int) graph[node].get(i);

                if(states[next] == 1) return false ;
                else if(states[next] == 0){
                    states[next] = 1;
                    queue.offer(next);
                }
            }
            states[node] = 2;
        }

        return count == n;
    }
}

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