LintCode 431: Connected Component in Undirected Graph (BFS/DFS/Union Find)

431. Connected Component in Undirected Graph

中文English

Find connected component in undirected graph.

Each node in the graph contains a label and a list of its neighbors.

(A connected 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.)

You need return a list of label set.

Example

Example 1:

Input: {1,2,4#2,1,4#3,5#4,1,2#5,3}
Output: [[1,2,4],[3,5]]
Explanation:

  1------2  3
   \     |  | 
    \    |  |
     \   |  |
      \  |  |
        4   5

Example 2:

Input: {1,2#2,1}
Output: [[1,2]]
Explanation:

  1--2

Clarification

Learn more about representation of graphs

Notice

Nodes in a connected component should sort by label in ascending order. Different connected components can be in any order.

Input test data (one parameter per line)How to understand a testcase?

 

解法1:BFS

代码如下:
 

/**
 * Definition for Undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */


class Solution {
public:
    /*
     * @param nodes: a array of Undirected graph node
     * @return: a connected set of a Undirected graph
     */
    vector<vector<int>> connectedSet(vector<UndirectedGraphNode*> nodes) {
        if (nodes.size() == 0) return result;
        for (auto node : nodes) visited[node] = 0;
        for (auto node : nodes) {
            if (!visited[node]) {
                visited[node] = 1;
                bfs(node, nodes);
            }
        }
        return result;
    }

private:
    void bfs(UndirectedGraphNode * node, vector<UndirectedGraphNode *> nodes)
    {
        queue<UndirectedGraphNode *> q;
        q.push(node);
        vector<int> component;
        component.push_back(node->label);
        while(!q.empty()) {
            UndirectedGraphNode * topNode = q.front();
            q.pop();
            for (int i = 0; i < topNode->neighbors.size(); ++i) {
                if (visited[topNode->neighbors[i]]) continue;
                visited[topNode->neighbors[i]] = 1;
                q.push(topNode->neighbors[i]);
                component.push_back(topNode->neighbors[i]->label);
            }
        }
        sort(component.begin(), component.end());
        result.push_back(component);
    } 
    
    vector<vector<int>> result;
    map<UndirectedGraphNode *, int> visited;
};

解法2:DFS

TBD

 

解法3:Union Find
TBD

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值