Find the Connected Component in the Undirected Graph
最后更新于:2022-04-02 01:13:38
# Find the Connected Component in the Undirected Graph
### Source
- lintcode: [(431) Find the Connected Component in the Undirected Graph](http://www.lintcode.com/en/problem/find-the-connected-component-in-the-undirected-graph/)
### Problem
Find the number connected component in the undirected graph. Each node in thegraph contains a label and a list of its neighbors. (a connected component (orjust component) of an undirected graph is a subgraph in which any two verticesare connected to each other by paths, and which is connected to no additionalvertices in the supergraph.)
#### 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}`
### 题解1 - [DFS](# "Depth-First Search, 深度优先搜索")
深搜加哈希表(因为有环,必须记录节点是否被访问过)
### Java
~~~
/**
* Definition for Undirected graph.
* class UndirectedGraphNode {
* int label;
* ArrayList neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); }
* }
*/
public class Solution {
/**
* @param nodes a array of Undirected graph node
* @return a connected set of a Undirected graph
*/
public List
';
- > connectedSet(ArrayList
- > result = new ArrayList
- >();
Set
- > connectedSet(ArrayList
- > result = new ArrayList
- >();
// log visited node before push into queue
Set