我正在阅读 Robert Sedwick 所著的《C++ 算法》一书。以下是关于复合数据结构的书中给出的示例。
问题陈述: 给定“d”,我们想知道单位正方形中的一组 N 点中有多少对可以通过长度小于“d”的直线连接。
下面的程序使用该逻辑将单位方格划分为网格,并维护一个二维链表数组,每个网格方格对应一个列表。网格选择得足够细,使得距离“d”内的所有点要么位于同一网格方 block 中,要么位于相邻网格方 block 中。
我的问题是
- Why author is allocating G+2 in malloc2d(G+2, G+2) ?
- In gridinsert function why author is performing following statement int X = x*G+1; int Y = y*G+1; ?
- In for loop why we are having i intialiazed to X-1 and j initialized to Y-1?
- 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;
}
最佳答案
这个想法是检查网格的所有相邻单元格。但边界单元没有相邻单元。因此,为了避免棘手的边界检查,我们将网格扩展了 2 个额外的单元格 - 在第一个单元格之前和最后一个单元格之后。这些单元格是“虚拟的”单元格,永远不会包含任何点 - 它们只是为了简化算法并为边界单元格提供相邻点。
(X,Y) - 包含该点的网格中单元格的坐标(索引)。根据 p.1,我们必须从单元格 (1,1) 开始放置点,而不是 (0,0)。 (0,0) 和任何其他边界点都是虚拟的。
因为我们检查网格的所有相邻单元格。 (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 的循环。
我们不维护它们,只是检查任何输入点与现有集,并在每次与距离匹配时递增计数器
cnt
。问题情况不需要保留此类对的列表。如果您需要保留点列表,您应该修改gridinsert()
,例如将(s->p, t->p)
放置到循环内的某个容器中,而不是递增cnt++
。
关于c++ - 使用复合数据结构计算最近点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12003038/