c++ - 使用复合数据结构计算最近点

标签 c++ algorithm computational-geometry

我正在阅读 Robert Sedwick 所著的《C++ 算法》一书。以下是关于复合数据结构的书中给出的示例。

问题陈述: 给定“d”,我们想知道单位正方形中的一组 N 点中有多少对可以通过长度小于“d”的直线连接。

下面的程序使用该逻辑将单位方格划分为网格,并维护一个二维链表数组,每个网格方格对应一个列表。网格选择得足够细,使得距离“d”内的所有点要么位于同一网格方 block 中,要么位于相邻网格方 block 中。

我的问题是

  1. Why author is allocating G+2 in malloc2d(G+2, G+2) ?
  2. In gridinsert function why author is performing following statement int X = x*G+1; int Y = y*G+1; ?
  3. In for loop why we are having i intialiazed to X-1 and j initialized to Y-1?
  4. Where in code we are maintaining points within distance d in same grid square or an adjacent one?

请求您通过简单的示例帮助理解以下程序。

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
using namespace std;


float randFloat() {
    return 1.0*rand()/RAND_MAX;
}


struct myPoint {
    float x;
    float y;
};

float myDistance(myPoint a, myPoint b) {
    float dx = a.x - b.x, dy = a.y - b.y;
    return sqrt(dx*dx + dy*dy);
}

struct node {
    myPoint p; node *next; 
    node(myPoint pt, node* t) {
        p = pt; next = t;
    }
};

typedef node *link;
static link **grid = NULL; 

link **malloc2d(int r, int c) {
    link **t = new link*[r];
    for (int i = 0; i < r; i++) {
      t[i] = new link[c];
    }
    return t;
 }

static int G, cnt = 0; 
static float d;

void gridinsert(float x, float y) {
    int X = x*G+1;
    int Y = y*G+1;
    myPoint p;
    p.x = x; p.y = y;
    link s, t = new node(p, grid[X][Y]);
    for (int i = X-1; i <= X+1; i++)
      for (int j = Y-1; j <= Y+1; j++)
        for (s = grid[i][j]; s != 0; s = s->next)
           if (myDistance(s->p, t->p) < d) cnt++; 

    grid[X][Y] = t;
 }

int main(int argc, char *argv[]) { 

    int i; 
    int N = 10;
    d = 0.25;
    G = 1/d;

    grid = malloc2d(G+2, G+2);
    for (i = 0; i < G+2; i++)
        for (int j = 0; j < G+2; j++)
            grid[i][j] = 0;

    for (i = 0; i < N; i++)
        gridinsert(randFloat(), randFloat());

    cout << cnt << " pairs within " << d << endl;

   return 0;
 }

最佳答案

  1. 这个想法是检查网格的所有相邻单元格。但边界单元没有相邻单元。因此,为了避免棘手的边界检查,我们将网格扩展了 2 个额外的单元格 - 在第一个单元格之前和最后一个单元格之后。这些单元格是“虚拟的”单元格,永远不会包含任何点 - 它们只是为了简化算法并为边界单元格提供相邻点。

  2. (X,Y) - 包含该点的网格中单元格的坐标(索引)。根据 p.1,我们必须从单元格 (1,1) 开始放置点,而不是 (0,0)。 (0,0) 和任何其他边界点都是虚拟的。

  3. 因为我们检查网格的所有相邻单元格。 (X,Y) 的相邻单元格为 (X-1,Y-1)、(X, Y-1)、(X+1, Y-1) 等至 (X+1,Y+1)。这就是为什么我们有从 X-1 到 X+1 和 Y-1 到 Y+1 的循环。

  4. 我们不维护它们,只是检查任何输入点与现有集,并在每次与距离匹配时递增计数器cnt。问题情况不需要保留此类对的列表。如果您需要保留点列表,您应该修改gridinsert(),例如将 (s->p, t->p) 放置到循环内的某个容器中,而不是递增 cnt++

关于c++ - 使用复合数据结构计算最近点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12003038/

相关文章:

c++ - 指针应该在哪里?

c++ - 如何在 C++ 中编写 FCC、BCC 和 HCP 晶格数组

ios - 黑白 UIImage 中的连通区域检测(blob 检测)

python - 获取字典中值满足条件的所有项目

javascript - 我查找数组最大元素的算法的缺陷在哪里?

c++ - qt小部件位置

c++ - 通过vba for mac在Excel中加载dylib

algorithm - 3D 中截留雨水的最大体积

algorithm - 由路径定义的两个多边形的并集

c - 用于查找两个 2D 四边形交点的 C 算法?