根据距离求cluster

题目:

在这里插入图片描述

解法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:
            graph[points[i]].add(points[j])
            graph[points[j]].add(points[i])

def helper(point):
    global cluster
    if point in visited:
        return
    visited.add(point)
    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

    def add_cluster(self,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)):
    uf.add_cluster(points[i])
    for j in range(i+1,len(points)):
        uf.add_cluster(points[j])
        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)
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页