问题
给定一系列的点。和一个矩形。求矩形中包括的点的数量。
解答
这个问题能够通过建立矩阵来进行求解。首先将一个空间切割成矩阵,将点放置在相应的格子中。再计算矩形覆盖的格子。再推断格子中的点是否包括在矩形中
这样的方法的问题是,可能这些点全都集中在一个格子中。
这样的情况下算法的效率比較低。
这样的问题在地图的应用中很常见。
因此须要引入2D树的概念,使得矩阵的分解会依据点的密度自己主动适应。
2D树
下图展示了2D树的样子。
2D树的构建
每次增加一个点时,将平面分成两半。
增加第二个点时。因为第二个点在第一个点的右側,因此在第一个点的右子节点创建一个新的节点。因为父节点是竖直的,所以子节点须要水平切割。
添加很多其它的点之后。就会形成例如以下的二叉树。
搜索操作
搜索矩形中包括的点。
搜索的时候须要从根节点開始。
从根节点知道,矩形在节点的左側。因此仅仅须要搜索左側就可以。到了点3。因为矩形覆盖了两边的区域。因此须要搜索两边。
一直迭代循环,直到节点搜索完成为止。
这样的算法的平均复杂度是logN。最坏复杂度是sqrtN。
问题
给定一系列点。和一个待測点。求与待測点近期的点。
用2D树的数据结构时,有时能够将搜索范围缩小到一半。
Kd树就是2D树的推广形式。处理二维以上的数据时很高效。
N体模拟算法
关键思想就是对于单个质点来说,将距离较远的那些点看成一个质点。
详细实现能够參考论文
http://www.cs.montana.edu/courses/spring2005/580/papers/0906008.pdf