1. 程式人生 > >LeetCode 261. Graph Valid Tree(判斷圖是否為樹)

LeetCode 261. Graph Valid Tree(判斷圖是否為樹)

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.

For example:

Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.

Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]

, return false.

Hint:

  1. Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree?
  2. According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”

注意,這裡的樹是普通的樹,不是二叉樹!

思路:要判斷一個圖是否為樹,首先要知道樹的定義。

一棵樹必須具備如下特性:

(1)是一個全連通圖(所有節點相通)

(2)無迴路

其中(2)等價於:(3)圖的邊數=節點數-1

因此我們可以利用特性(1)(2)或者(1)(3)來判斷。

方法一:廣度優先搜尋。要判斷連通性,廣度優先搜尋法是一個天然的選擇,時間複雜度O(n),空間複雜度O(n)。

public class Solution {
    public boolean validTree(int n, int[][] edges) {
        Map<Integer, Set<Integer>> graph = new HashMap<>();
        for(int i=0; i<edges.length; i++) {
            for(int j=0; j<2; j++) {
                Set<Integer> pairs = graph.get(edges[i][j]);
                if (pairs == null) {
                    pairs = new HashSet<>();
                    graph.put(edges[i][j], pairs);
                }
                pairs.add(edges[i][1-j]);
            }
        }
        Set<Integer> visited = new HashSet<>();
        Set<Integer> current = new HashSet<>();
        visited.add(0);
        current.add(0);
        while (!current.isEmpty()) {
            Set<Integer> next = new HashSet<>();
            for(Integer node: current) {
                Set<Integer> pairs = graph.get(node);
                if (pairs == null) continue;
                for(Integer pair: pairs) {
                    if (visited.contains(pair)) return false;
                    next.add(pair);
                    visited.add(pair);
                    graph.get(pair).remove(node);
                }
            }
            current = next;
        }
        return visited.size() == n;
    }
}
public class Solution {
    private boolean[] visited;
    private int visits = 0;
    private boolean isTree = true;
    private void check(int prev, int curr, List<Integer>[] graph) {
        if (!isTree) return;
        if (visited[curr]) {
            isTree = false;
            return;
        }
        visited[curr] = true;
        visits ++;
        for(int next: graph[curr]) {
            if (next == prev) continue;
            check(curr, next, graph);
            if (!isTree) return;
        }
        
    }
    public boolean validTree(int n, int[][] edges) {
        visited = new boolean[n];
        List<Integer>[] graph = new List[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]);
        }
        check(-1, 0, graph);
        return isTree && visits == n;
    }
}

方法三:按節點大小對邊進行排序,原理類似並查集。

public class Solution {
    public boolean validTree(int n, int[][] edges) {
        if (edges.length != n-1) return false;
        Arrays.sort(edges, new Comparator<int[]>() {
           @Override
           public int compare(int[] e1, int[] e2) {
               return e1[0] - e2[0];
           }
        });
        int[] sets = new int[n];
        for(int i=0; i<n; i++) sets[i] = i;
        for(int i=0; i<edges.length; i++) {
            if (sets[edges[i][0]] == sets[edges[i][1]]) return false;
            if (sets[edges[i][0]] == 0) {
                sets[edges[i][1]] = 0;
            } else if (sets[edges[i][1]] == 0) {
                sets[edges[i][0]] = 0;
            } else {
                sets[edges[i][1]] = sets[edges[i][0]];
            }
        }
        return true;
    }
}

方法四:Union-Find

public class Solution {
    public boolean validTree(int n, int[][] edges) {
        if (edges.length != n-1) return false;
        int[] roots = new int[n];
        for(int i=0; i<n; i++) roots[i] = i;
        for(int i=0; i<edges.length; i++) {
            int root1 = root(roots, edges[i][0]);
            int root2 = root(roots, edges[i][1]);
            if (root1 == root2) return false;
            roots[root2] = root1;
        }
        return true;
    }
    private int root(int[] roots, int id) {
        if (id == roots[id]) return id;
        return root(roots, roots[id]);
    }
}

參考文章: