zoukankan      html  css  js  c++  java
  • 261. Graph Valid Tree

    package LeetCode_261
    
    import java.util.*
    
    
    /**
     * 261. Graph Valid Tree
     * Lock by leetcode
     * https://www.lintcode.com/problem/graph-valid-tree/description
     *
     * 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.
    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.
     * */
    class Solution {
        /*
        * valid Tree, must a connected graph and acyclic
        * */
        fun validTree(n: Int, edges: Array<IntArray>): Boolean {
            val graph = HashMap<Int, ArrayList<Int>>()
            //init
            for (i in 0 until n) {
                graph[i] = ArrayList()
            }
            //create graph
            for (edge in edges) {
                graph[edge.get(0)]!!.add(edge.get(1))
                graph[edge.get(1)]!!.add(edge.get(0))
            }
    
            val visited = BooleanArray(n)
    
            val queue = LinkedList<Int>()
    
            queue.offer(0)
    
            while (!queue.isEmpty()) {
                val top = queue.poll()
                if (visited[top]) {
                    return false
                }
                visited[top] = true
                val list = graph[top]
                if (list == null) {
                    continue
                }
                for (item in list) {
                    if (!visited[item]) {
                        queue.offer(item)
                    }
                }
            }
    
            for (v in visited) {
                if (!v) {
                    return false
                }
            }
    
            return true
        }
    }
  • 相关阅读:
    [BZOJ2431] [HAOI2009]逆序对数列
    [Luogu2323] [HNOI2006]公路修建问题
    [Luogu2455] [SDOI2006]线性方程组
    [BZOJ3550] [Sdoi2014]数数
    [Noip2017] 列队
    [Luogu2824] [HEOI2016/TJOI2016]排序
    [BZOJ1060] [ZJOI2007]时态同步
    P1036 选数 题解
    快速幂取模算法详解
    同余定理及其应用
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/12736487.html
Copyright © 2011-2022 走看看