261. Graph Valid Tree

Medium
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.

Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.

解法一
用并查集做特别简单,记下模版就可以,不过有个地方要注意理解一下, 就是如何判断图中有环那里。if(find(edges[i][0]) == find(edges[i][1])){ return false;} 意思就是如果还没连edges之前,两个node的祖先就是一个,那他们要试连起来,肯定就有环了,很好理解吧。还要注意,如果是tree, graph里面vertices数目和edges数目之间有个固定的关系:e = v - 1, 这两点理解好了,这道题用并查集非常简单。

class Solution {
    private int[] father;
    public boolean validTree(int n, int[][] edges) {
        father = new int[n];
        for (int i = 0; i < n; i++){
            father[i] = i;
        }    
        for (int i = 0; i < edges.length; i++){
            if(find(edges[i][0]) == find(edges[i][1])){
                return false;
            }
            connect(edges[i][0], edges[i][1]);
        }
        return edges.length == n - 1;
    }
    
    private int find(int x){
        if (father[x] == x){
            return x;
        }
        return find(father[x]);
    }
    
    private void connect(int a, int b){
        int root_a = find(a);
        int root_b = find(b);
        if (root_a != root_b){
            father[root_a] = root_b;
        }
    }
}

解法二
BFS
就用固定套路吧,先建图(通常都是邻接表)。建图很简单,map的key对应每个 vertice, value对应每个vertice的neighbors,用arraylist表示。 遍历edges,每个edge[] 分别代表一条edge的两端,分别加到彼此的邻居里。这里有一个E = V – 1要注意,如果不满足就直接返回false. 用Queue做bfs, 用一个boolean[] visited记录是否访问过,先把0放进去。每次从queue里取出一个,如果这个已经被访问过,立马返回false. 为什么?这种情况只可能出现在环里,你在queue里放进去过这个元素好几次。 然后访问poll出来这个点的邻接表,把没有访问过的元素offer到队列。最后我们要保证每个元素都被访问过,如果有没访问过的就返回false.

class Solution {
    public boolean validTree(int n, int[][] edges) {
        Map<Integer, ArrayList<Integer>> neighbors = new HashMap<>();
        buildGraph(n, edges, neighbors);
        if (edges.length != n - 1){
            return false;
        }
        Queue<Integer> queue = new LinkedList<>();
        boolean[] visited = new boolean[n]; 
        queue.offer(0);
        while (!queue.isEmpty()){
            Integer curt = queue.poll();
            if (visited[curt]){
                return false;
            }
            visited[curt] = true;
            for (Integer nei : neighbors.get(curt)){
                if (!visited[nei]){
                    queue.offer(nei);
                } 
            }
        }
        for (boolean b : visited){
            if (!b){
                return false;
            }
        }
        return true;
    }

    private void buildGraph(int n, int[][] edges, Map<Integer, ArrayList<Integer>> neighbors){
        for (int i = 0; i < n; i++){
            neighbors.put(i, new ArrayList<Integer>());
        }    
        for (int i = 0; i < edges.length; i++){
            int u = edges[i][0];
            int v = edges[i][1];
            neighbors.get(u).add(v);
            neighbors.get(v).add(u);
        }
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/54d719cae3f4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞