码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Graph Valid Tree"

时间:2015-08-21 14:59:18      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

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

LeetCode "Graph Valid Tree"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4747541.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!