Connected Component in Undirected Graph
Description
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.
Nodes in a connected component should sort by label in ascending order. Different connected components can be in any order.
Similar problem
leetcode 323 number-of-connected-components-in-an-undirected-graph
Code
def connectedSet(self, nodes: List[UndirectedGraphNode]) -> List[List[int]]:
if not nodes:
return []
queue = collections.deque()
visited = set()
res = []
for node in nodes:
if node in visited:
continue
queue.append(node)
visited.add(node)
subgraph = []
while queue:
current_node = queue.popleft()
subgraph.append(current_node.label)
for neighbor in current_node.neighbors:
if neighbor in visited:
continue
queue.append(neighbor)
visited.add(neighbor)
subgraph.sort()
res.append(subgraph)
return res