[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);
            }
        }
    }
};
    原文作者:楷书
    原文地址: https://www.jianshu.com/p/79e9c8704be4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞