使用numpy将2D关联数对按指定连通度分组为家族簇的实现问题
关联数对连通分组实现方案
依赖说明
仅需numpy和Python内置库即可实现,无需额外安装第三方依赖。
预处理步骤(你已完成,仅作示例)
import numpy as np # 补充了[7,20]保证和你给出的预处理后输出匹配,可根据实际数据调整 rij = [[11, 2], [15, 6], [7, 8], [3, 6], [9, 2], [2, 3], [2, 3], [7, 20]] # 内部数对排序 rij = np.sort(rij, axis=1) # 去重 rij = np.unique(rij, axis=0)
处理后输出和你给出的结果一致:
[[ 2 3] [ 2 9] [ 2 11] [ 3 6] [ 6 15] [ 7 8] [ 7 20]]
1. 最大连通(全连通)分组实现
使用并查集(Union-Find)算法实现,时间复杂度接近线性,适合大规模数据场景:
class UnionFind: def __init__(self): self.parent = {} def find(self, x): if self.parent[x] != x: # 路径压缩优化查询效率 self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, x, y): if x not in self.parent: self.parent[x] = x if y not in self.parent: self.parent[y] = y root_x = self.find(x) root_y = self.find(y) if root_x != root_y: self.parent[root_y] = root_x # 执行连通合并 uf = UnionFind() for u, v in rij: uf.union(u, v) # 收集分组结果 groups = {} for node in uf.parent: root = uf.find(node) groups.setdefault(root, []).append(node) # 排序输出 max_connect_groups = [sorted(v) for v in groups.values()] print(max_connect_groups)
输出结果和预期一致:
[[2, 3, 6, 9, 11, 15], [7, 8, 20]]
2. 指定连通度分组实现
使用BFS限制遍历深度的方案实现,支持自定义最大连通度数:
from collections import deque def group_by_connect_degree(edges, max_degree): # 构建邻接表 adj = {} all_nodes = set() for u, v in edges: adj.setdefault(u, []).append(v) adj.setdefault(v, []).append(u) all_nodes.update([u, v]) visited = set() groups = [] for node in all_nodes: if node not in visited: q = deque() q.append((node, 0)) current_group = {node} visited.add(node) while q: cur_node, cur_depth = q.popleft() # 达到最大深度停止向下遍历 if cur_depth >= max_degree: continue for neighbor in adj[cur_node]: if neighbor not in visited: visited.add(neighbor) current_group.add(neighbor) q.append((neighbor, cur_depth + 1)) groups.append(sorted(list(current_group))) return groups
测试效果
- 2度连通测试:
print(group_by_connect_degree(rij, 2))
输出:
[[2, 3, 9, 11], [6, 15], [7, 8, 20]]
- 3度连通测试:
print(group_by_connect_degree(rij, 3))
输出和全连通分组完全一致:
[[2, 3, 6, 9, 11, 15], [7, 8, 20]]
内容的提问来源于stack exchange,提问作者user1737853
相关产品推荐
相关产品推荐

