zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    罗素语录
    《一步一步写嵌入式操作系统》读书笔记1—Skyeye介绍、安装和HelloWorld
    在Raspberry Pi上安装XBMC
    Raspberry Pi上手
    axios案例
    php+mysql修改数据库数据
    将前台输入的“意见反馈”提交到后台数据库
    用JavaScript动态生成HTML(PHP+MYSQL)(2)
    用JavaScript动态生成HTML(PHP+MYSQL)(1)
    SQL课堂笔记--设计数据库
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7723348.html
Copyright © 2011-2022 走看看