240
笔下虽有千言,胸中实无一策

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;
    }
};
posted @ 2020-10-02 14:17  CasperWin  阅读(61)  评论(0编辑  收藏  举报