# 解法1：graph+dfs

import math
import collections
def cal_dis(x1,y1,x2,y2):
return math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))

k = 7
points = [(0,1),(0,2),(0,3),(0,4),(0,10),(0,11),(0,100),(0,101)]

graph = collections.defaultdict(set)

for i in range(len(points)):
for j in range(i+1,len(points)):
if cal_dis(points[i][0],points[i][1],points[j][0],points[j][1])<k:

def helper(point):
global cluster
if point in visited:
return
cluster.append(point)
for neigh in graph[point]:
helper(neigh)

visited = set()
ans = []
for point in points:
cluster = []
helper(point)
if cluster:
ans.append(cluster)


# 解法2：union find

import math
import collections
class UnionFind():
def __init__(self):
self.clusters = {}

def find(self,p):
while p != self.clusters[p]:
p = self.clusters[p]
return p

if p not in self.clusters:
self.clusters[p] = p

def union(self,p,q):
self.clusters[p] = self.clusters[q]

def cal_dis(x1,y1,x2,y2):
return math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))

k = 2
points = [(0,1),(0,2),(0,3),(0,6),(0,10),(0,11),(0,100),(0,101),(0,102)]

uf = UnionFind()
for i in range(len(points)):
for j in range(i+1,len(points)):
if cal_dis(points[i][0],points[i][1],points[j][0],points[j][1])<k:
uf.union(points[i],points[j])
ans = collections.defaultdict(list)
for k,v in uf.clusters.items():
ans[uf.find(k)].append(k)
print(ans)

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

努利！奋斗！

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
06-30 848
03-15 42

01-04 4879
11-06
01-30 998
08-02 2万+
01-31 165
02-07 398
02-12 34
01-27 569