我正在尝试使用分治法来完成两点的最接近对,但是当我将其与具有相同输入的蛮力版本进行比较时,它并不总是给我正确的最小距离。这些点在列表中由一组(x,y)表示。变量list1按x坐标值升序排序,list2按y坐标值升序排序。知道这里有什么问题吗?
def cp_dq(list1, list2):
if len(list1) <= 3:
return bf_cp(list1)
else:
list1_left = list1[:len(list1) // 2]
list1_right = list1[len(list1) // 2:]
list2_left = list2[:len(list1) // 2]
list2_right = list2[len(list1) // 2:]
distance_left = cp_dq(list1_left, list2_left)
distance_right = cp_dq(list1_right, list2_right)
distance = min(distance_left,distance_right)
median_x = list1[(len(list1) // 2) - 1][0]
s_list = []
for point in list2:
if abs(point[0] - median_x) < distance:
s_list.append(point)
min_d_sq = distance**2
j = 0
for i in range(len(s_list)-1):
j = i+1
while j<=len(s_list)-1 and (s_list[j][1]-s_list[i][1])**2 < min_d_sq:
min_d_sq = min((s_list[j][0]-s_list[i][0])**2+(s_list[j][1]-s_list[i][1])**2, min_d_sq)
j+=1
return math.sqrt(min_d_sq)