[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 graphsExample
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);
}
}
}
};
相關文章
- 翻譯|How to Export a Connected ComponentExport
- Strongly connected(HDU-4635)
- Paper -- DenseNet:Densely Connected Convolutional NetworkSENet
- 記一次zookeeper not connected
- DFS
- [LintCode] Daily TemperaturesAI
- [LintCode] Permutation in String
- Codeforces Round #689 (Div. 2, based on Zed Code Competition)-B. Find the Spruce(DFS+記憶化搜尋)Zed
- dfs序
- DFS樹
- dfs技巧
- 【Lintcode】1189. Minesweeper
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- Lintcode 1263. Is Subsequence
- 深搜dfs
- Tempter of the Bone(DFS)
- 什麼是@Component,@Component的作用是什麼
- [LintCode] Binary Tree Level Order
- 【Lintcode】1615. The Result of Investment
- 【Lintcode】1218. Number Complement
- 【Lintcode】1850. Pick ApplesAPP
- 【Lintcode】1562. Number of RestaurantsREST
- 【Lintcode】141. Sqrt(x)
- 【Lintcode】576. Split Array
- 【Lintcode】1267. Lexicographical Numbers
- 【Lintcode】1732. Snakes and Ladders
- 【Lintcode】1230. Assign CookiesCookie
- 【Lintcode】1665. Calculate Number
- 【Lintcode】1415. Residual Product
- 【Lintcode】1789. Distinguish UsernameNGUI
- 【Lintcode】318. Character Grid
- 【Lintcode】572. Music PairsAI
- 【Lintcode】1736. Throw Garbage
- 【Lintcode】1891. Travel Plan
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- [LintCode] 3Sum Smaller