根据距离求cluster

题目:

根据距离求cluster_第1张图片

解法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)

你可能感兴趣的:(Leetcode,DFS,Leetcode,UnionFind,python,算法)