我有一套给定位置和半径在二维平面上的圆。我想确定每个圆是否与任何其他圆相交以及将两者分开所需的距离。在我目前的实施中,我只是通过所有可能的圆组合,然后进行计算。不幸的是,这个算法是O(n^2),这很慢。圆分离距离 - 最近邻问题
这些圈子通常会聚集在一起,它们将具有相似(但不同)的半径。圆的数量的近似最大值大约为200.算法不一定是确切的,但应该是接近的。
这里是一个(慢)实现我目前在JavaScript中:
// Makes a new circle
var circle = function(x,y,radius) {
return {
x:x,
y:y,
radius:radius
};
};
// These points are not representative of the true data set. I just made them up.
var points = [
circle(3,3,2),
circle(7,5,4),
circle(16,6,4),
circle(17,12,3),
circle(26,20,1)
];
var k = 0,
len = points.length;
for (var i = 0; i < len; i++) {
for (var j = k; j < len; j++) {
if (i !== j) {
var c1 = points[i],
c2 = points[j],
radiiSum = c1.radius+c2.radius,
deltaX = Math.abs(c1.x-c2.x);
if (deltaX < radiiSum) {
var deltaY = Math.abs(c1.y-c2.y);
if (deltaY < radiiSum) {
var distance = Math.sqrt(deltaX*deltaX+deltaY*deltaY);
if (distance < radiiSum) {
var separation = radiiSum - distance;
console.log(c1,c2,separation);
}
}
}
}
}
k++;
}
此外,我将不胜感激,如果你解释用简单的英语好的算法(kd树): -/
看看这个答案http://stackoverflow.com/questions/3265986/an-algorithm-to-space-out-overlapping-矩形/ 3279877#3279877 – 2011-01-31 03:08:29
[Sweep and prune](http://en.wikipedia.org/wiki/Sweep_and_prune)可能值得研究。当然,它无助于实际的放置。另外一个“快速黑客”是为了检查而去除`sqrt`,因为对于正实数,sqrt(x)<= sqrt(y)`暗示`x <= y`。 – 2011-01-31 03:19:53