美文网首页LeetCode程序员
[LintCode][DFS] Find the Connect

[LintCode][DFS] Find the Connect

作者: 楷书 | 来源:发表于2016-04-15 07:22 被阅读67次

    Problem

    Find the number connected component in the undirected graph. Each node in the graph contains a label and a list of its neighbors. (a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph.)

    Clarification
    Learn more about representation of graphs

    Example
    Given graph:

    A------B  C
     \     |  | 
      \    |  |
       \   |  |
        \  |  |
          D   E
    

    Return {A,B,D}, {C,E}. Since there are two connected component which is {A,B,D}, {C,E}

    Solution

    DFS找出联通块

    /**
     * Definition for Undirected graph.
     * struct UndirectedGraphNode {
     *     int label;
     *     vector<UndirectedGraphNode *> neighbors;
     *     UndirectedGraphNode(int x) : label(x) {};
     * };
     */
    class Solution {
    private:
        set<int> visited;
    public:
        /**
         * @param nodes a array of Undirected graph node
         * @return a connected set of a Undirected graph
         */
        vector<vector<int>> connectedSet(vector<UndirectedGraphNode*>& nodes) {
            vector<vector<int>> ret;
            for(int i = 0; i < nodes.size(); i++) {
                if (visited.count(nodes[i]->label) == 0) {
                    vector<int> res;
                    visited.insert(nodes[i]->label);
                    dfs(nodes[i], res);
                    sort(res.begin(), res.end());
                    ret.push_back(res);
                }
            }
            return ret;
        }
        
        void dfs(UndirectedGraphNode *node, vector<int> &res) {
            res.push_back(node->label);
            for(int i = 0; i < node->neighbors.size(); i++) {
                int label = node->neighbors[i]->label;
                if (visited.count(label) == 0) {
                    visited.insert(label);
                    dfs(node->neighbors[i], res);
                }
            }
        }
    };
    

    相关文章

      网友评论

        本文标题:[LintCode][DFS] Find the Connect

        本文链接:https://www.haomeiwen.com/subject/hhqnlttx.html