[LintCode][DFS] Find the Connected Component in the Undirected Graph

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);
            }
        }
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容