线段搜索的最佳数据结构是什么?

时间:2011-12-19 08:51:48

标签: c# algorithm data-structures kdtree

我需要一个数据结构来查找落在矩形中的所有段(在C#中,即使它不是主要问题)。

例如,段[(0,0),(10,10)]必须位于以(5,5)开头的大小为(1,1)的矩形中。

我尝试了kdtree,但只有当他的一个点正好在矩形中时,它才返回段。它没有看到该段是一个连续的线。

我需要什么样的数据结构才能有效地进行搜索? 我搜索但没有找到任何适合这种情况的东西,即使它看起来很标准!

问题尺寸:6000个线段,平均20个线段位于矩形

重复排序:

1 个答案:

答案 0 :(得分:0)

您可以尝试将扩展线段参数化为(y轴截距,斜率)或类似值。与给定线段相交的延长线的空间在(y-截距,斜率)空间中形成一个形状,您可以查询该形状,就好像这些线是点。 (处理垂直线作为特殊情况。)

获取与任何rect的边界线段相交的线的并集,然后过滤掉未延伸时实际上没有穿过矩形的线段。

// we will intersect against three of the rect's borders (the 4th's results are redundant)
borders = {(TopLeft, TopRight), (TopRight, BottomRight), (BottomRight, BottomLeft)}
// each border forms a shape in (y, slope) space defined by two intersecting half spaces
// we query the line space using something standard like kd-trees
lines1 = Union(borders.ForEach(LineSpace.Inside(ShapeOfSegmentInIntersectSpace(?border))))
// now filter out lines that don't cross the rect when extended
// since we already know they intersect when extended, the check is pretty simple
lines2 = lines1.Where(?line.BoundingRect.Intersects(rect))