[Lintcode] Graph Valid Tree

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.

 Notice

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.

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.

 

解题思路:

这题的思路还是比较巧妙的,满足一个图是树的前提是:

1,一定是有点的个数减一条边,即 edges = n (of nodes) - 1.

2,从起始点开始bfs一定可以遍历所有的点。例如: 1

                  /      \

                 2  ---- 3      4

上图的情况就是4个点3条边,但是有一个点孤立,有一个环,这种就不是树,要排除这种情况。

思路:

1,要构建一个图。也就是要表达出点与边的关系。

2,遍历所有的点,记录所有点的入度。

3,用Queue + set/map BFS。

4, 输出结果:看能否bfs所有点,实现就是看: set.size() == n。

 

 

public class Solution {
    /**
     * @param n an integer
     * @param edges a list of undirected edges
     * @return true if it's a valid tree, or false
     */
    public boolean validTree(int n, int[][] edges) {
        if (n == 0) {
            return false;
        }
        if (edges.length != n - 1) {
            return false;
        }
        Map<Integer, Set<Integer>> graph = constructGraph(n, edges);
        
        Queue<Integer> queue = new LinkedList<>();
        Set<Integer> set = new HashSet<Integer>();
        
        queue.offer(0);
        set.add(0);
        
        while (!queue.isEmpty()) {
            int node = queue.poll();
            for (Integer neighbor : graph.get(node)) {
                if (set.contains(neighbor)) {
                    continue;
                }
                set.add(neighbor);
                queue.offer(neighbor);
            }
        }
        return (set.size() == n);
    }
    private Map<Integer, Set<Integer>> constructGraph(int n, int[][] edges) {
        Map<Integer, Set<Integer>> graph = new HashMap<>();
        // initial
        for (int i = 0; i < n; i++) {
            graph.put(i, new HashSet<Integer>());
        }
        for (int i = 0; i < edges.length; i++) {
            int u = edges[i][0];
            int v = edges[i][1];
            graph.get(u).add(v);
            graph.get(v).add(u);
        }
        return graph;
    }
}
View Code

 

posted @ 2017-08-18 03:34  Tri_tri_tri  阅读(109)  评论(0)    收藏  举报