LeetCode "Graph Valid Tree"

DFS to check cyclic. Please note some details.

class Solution
{
    unordered_map<int, unordered_set<int>> g;
    unordered_set<int> visited;
    
    bool go(int i, int p) // true - cyclic
    {
        visited.insert(i);
        auto &cs = g[i];
        for (auto c : cs)
        {
            if (c == p) continue;
            if (visited.find(c) != visited.end()) return true;
            bool b = go(c, i);
            if (b) return true;
        }
        return false;
    }
public:
    bool validTree(int n, vector<pair<int, int>>& edges)
    {
        int vcnt = n - 1;
        int ecnt = edges.size();
        if (ecnt != vcnt) return false;
        
        //    Build Graphs
        for (auto &p : edges)
        {
            g[p.first].insert(p.second);
            g[p.second].insert(p.first);
        }

        //    DFS
        for (int i = 0; i < n; i++)
        {
            if (visited.find(i) == visited.end())
            {
                bool ret = go(i, -1);
                if (ret) 
                    return false;
            }
        }
        return true;
    }
};
View Code
原文地址:https://www.cnblogs.com/tonix/p/4747541.html