Connected Component in Undirected Graph

该博客探讨了如何在无向图中找到连接组件。每个节点包含标签和邻居列表。连通组件是指图中任意两个节点间存在路径,并且不与其他超图节点相连的子图。解决方案需要返回按标签升序排列的组件标签集合。
摘要由CSDN通过智能技术生成

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值