# Connected Component in Undirected Graph

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.)

## 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, 但是隐式DFS的模式大多都是在循环内把结果添加进入临时的current变量， 但是对于图不是特别适合，主要是图有邻居节点，简单的做法就是在利用isVisited 字典，只访问节点一次，第二添加结果集在DFS循环外。这道题的第二个重点就是，结果返回的label集合，而不是节点集合。

```
# Definition for a undirected graph node
# class UndirectedGraphNode:
#     def __init__(self, x):
#         self.label = x
#         self.neighbors = []
class Solution:
    # @param {UndirectedGraphNode[]} nodes a array of undirected graph node
    # @return {int[][]} a connected set of a undirected graph
    def connectedSet(self, nodes):
        # Write your code here
        isVisited = {}
        for node in nodes:
            isVisited[node.label] = False
        result = []
        for node in nodes:
            if not isVisited[node.label]:
                current = []
                self.DFS(isVisited, node, current)
                result.append(sorted(current))
        return result

    def DFS(self, isVisited, node, current):
        isVisited[node.label] = True
        current.append(node.label)
        for neighbor in node.neighbors:
            if not isVisited[neighbor.label]:
                self.DFS(isVisited, neighbor, current)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://liuxue2010.gitbook.io/data-structure-and-algorithms/graph/connected-component-in-undirected-graph.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
