[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 neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
private:
    set visited;
public:
    /**
     * @param nodes a array of Undirected graph node
     * @return a connected set of a Undirected graph
     */
    vector> connectedSet(vector& nodes) {
        vector> ret;
        for(int i = 0; i < nodes.size(); i++) {
            if (visited.count(nodes[i]->label) == 0) {
                vector 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 &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 Connected Component in the Undirected Graph)