zoukankan      html  css  js  c++  java
  • 30 Day Challenge Day 17 | Leetcode 261. Graph Valid Tree

    题解

    Medium

    BFS

    一个节点只计算一次,这一点要注意。

    class Solution {
    public:
        bool validTree(int n, vector<vector<int>>& edges) {
            vector<unordered_set<int>> graph(n, unordered_set<int>());
            for(auto e : edges) {
                graph[e[0]].insert(e[1]);
                graph[e[1]].insert(e[0]);
            }
            
            unordered_set<int> visited;
            
            queue<int> q;
            q.push(0);
            
            while(!q.empty()) {
                int t = q.front();
                q.pop();
                
                if(visited.count(t)) return false; // cycle detected
                visited.insert(t);
                
                for(auto i : graph[t]) {
                    q.push(i);
                    graph[i].erase(t); // node in one edge counts once
                }
            }
            
            return visited.size() == n;
        }
    };
    
  • 相关阅读:
    Matlab 画图
    OfferCome-0531
    OfferCome--0528
    剑指offer(2)
    剑指offer(1)
    MySQL的自增主键
    java Junit 测试
    sql 注入问题
    Facebook Libra
    markdown的博客
  • 原文地址:https://www.cnblogs.com/casperwin/p/13761310.html
Copyright © 2011-2022 走看看