lintcode178- Graph Valid Tree- medium

Posted jasminemzy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode178- 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.

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. 点 = 边 + 1

2. 所有点连通(判断条件不是所有点都有相邻点,而是要灌水法BFS从一个点搜出去看能不能碰到所有点)。

实现:两个步骤,1.初始化建立邻接表 Map<Integer, Set<Integer>> 2.BFS(queue + set),从第一个点0开始拓展出去BFS,如果最后set.size() == n才合格。

注意一下 Map: containsKey() + put() + get(key).  Set: contains() + add(). List: contains() + add() + get(index);

 

1. 自己实现

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) {
        // write your code here
        
        if (edges == null || edges.length == 0) {
            if (n == 1) {
                return true;
            } else {
                return false;
            }
        }
        
        if (n != edges.length + 1 ) {
            return false;
        }
        
        Map<Integer, Set<Integer>> neighborMap = initGraph(n,edges);
        //注意:大家都有邻居是不够的,如果都有邻居但是分成两个小团体也不行
        // if (neighberMap.size() < n) {
        //     return false;
        // }
        Queue<Integer> queue = new LinkedList<Integer>();
        Set<Integer> set = new HashSet<Integer>();
        
        queue.offer(0);
        set.add(0);
        while (!queue.isEmpty()) {
            int node = queue.poll();
            Set<Integer> neighbors = neighborMap.get(node);
            if (neighbors == null) {
                return false;
            }
            for (int neighbor : neighbors) {
                if (!set.contains(neighbor)) {
                    set.add(neighbor);
                    queue.offer(neighbor);
                }
            }
        }
        
        if (set.size() != n) {
            return false;
        }
        return true;
    }
    
    private Map<Integer, Set<Integer>> initGraph(int n, int[][] edges) {
        
        Map<Integer, Set<Integer>> map = new HashMap<>();
        for (int i = 0; i < edges.length; i++) {
            int n1 = edges[i][0];
            int n2 = edges[i][1];
            // map的一定是containsKey或者containsValue + put!不是contains!!!
            // set的是contains + add!!
            if (!map.containsKey(n1)) {
                Set<Integer> set = new HashSet<Integer>();
                set.add(n2);
                map.put(n1, set);
            } else {
                map.get(n1).add(n2);
            }
            
            if (!map.containsKey(n2)) {
                Set<Integer> set = new HashSet<Integer>();
                set.add(n1);
                map.put(n2, set);
            } else {
                map.get(n2).add(n1);
            }
        }
        return map;
    }
}

 

2.九章实现

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 = initializeGraph(n, edges);
        
        // bfs
        Queue<Integer> queue = new LinkedList<>();
        Set<Integer> hash = new HashSet<>();
        
        queue.offer(0);
        hash.add(0);
        while (!queue.isEmpty()) {
            int node = queue.poll();
            for (Integer neighbor : graph.get(node)) {
                if (hash.contains(neighbor)) {
                    continue;
                }
                hash.add(neighbor);
                queue.offer(neighbor);
            }
        }
        
        return (hash.size() == n);
    }
    
    private Map<Integer, Set<Integer>> initializeGraph(int n, int[][] edges) {
        Map<Integer, Set<Integer>> graph = new HashMap<>();
        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;
    }
}

 

以上是关于lintcode178- Graph Valid Tree- medium的主要内容,如果未能解决你的问题,请参考以下文章

[LintCode] Graph Valid Tree

[LintCode] Valid Parentheses

LintCode 777. Valid Perfect Square

lintcode-medium-Clone Graph

[LintCode] Clone Graph

Lintcode137.Clone Graph