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
该博客探讨了如何在无向图中找到连接组件。每个节点包含标签和邻居列表。连通组件是指图中任意两个节点间存在路径,并且不与其他超图节点相连的子图。解决方案需要返回按标签升序排列的组件标签集合。
639

被折叠的 条评论
为什么被折叠?



