無向圖如何檢測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;
    }
}

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