【问题标题】:How to find adjacent points in a 3D space in c++ [closed]如何在 C++ 中找到 3D 空间中的相邻点 [关闭]
【发布时间】:2018-04-10 22:41:13
【问题描述】:

我在 3D 空间中有几个点,我想编写一个条件来确定两个点是否相邻:它们在整数格中是否仅相隔一个单位?

我有一个名为 Point 的结构,它包含 x、y 和 z 坐标。然后在主函数中,我设置点 a、b、c、d、e 的值并将它们推入向量中。然后在for循环中我想检查两个点是否相邻。目前我只是检查它们是否在同一轴上,但我不知道如何进行。

struct Point{
   int x;
   int y;
   int z;
};

int main(){
    // just a couple of points
    struct Point a;
    struct Point b;
    struct Point c;
    struct Point d;
    struct Point e;

    vector<Point> pointVector;

    a.x = 0 ; a.y = 0; a.z = 0;
    b.x = 0; b.y = 0; b.z = -1;
    c.x = 1; c.y = 0; c.z = -1;
    d.x = 1; d.y = -1; d.z = -1;
    e.x = 2; e.y = -1; e.z = -1;

    pointVector.push_back(a);
    pointVector.push_back(b);
    pointVector.push_back(c);
    pointVector.push_back(d);
    pointVector.push_back(e);

    for(int i = 0; i < 5; i++){
       if(pointVector[i].x == pointVector[i+1].x ||  // how to set the condition to check if two points are adjacent?
          pointVector[i].y == pointVector[i+1].y || 
          pointVector[i].z == pointVector[i+1].z  
       ) cout << "adjacent" << endl;
       else
         cout << "not adjacent" << endl;


    }



    return 0;
}

相邻是指这张照片中的内容:

【问题讨论】:

  • 我们需要您为此应用程序定义“相邻”。
  • @Prune 我添加了一张图片,其中“点”连接并且相邻的点直接相互连接
  • 我想我明白了:你需要坐标在一个轴上正好相差 1。你能写出这个逻辑吗?
  • @Prune 完全正确。而且我不知道如何解决这种问题。编码不是我需要理解逻辑的问题。一旦我有了它,一切都很好:)

标签: c++ algorithm adjacency-list


【解决方案1】:

非常简短:

for each pair of points:
    if two of the three coordinates are equal AND
              the other coordinate differs by 1:
        then mark the pair as adjacent.

遍历点对很简单:第一个点 a 遍历索引 0-(n-2);第二点b 遍历索引,从a 的位置到末尾n-1

给定整数坐标,检查邻接也很容易。

diff = abs(a.x - b.x) + 
       abs(a.y - b.y) + 
       abs(a.z - b.z)

diff = 1 iff 点是相邻的。

【讨论】:

  • 只是补充一下 - 可以使用 k-D 树将大量点的时间复杂度从 O(N^2) 降低到 O(N log N)。
  • @meowgoesthedog:谢谢!我一直忘记这些......我猜是显示我的年龄。
猜你喜欢
  • 2021-07-22
  • 1970-01-01
  • 2019-06-04
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
  • 2020-09-09
  • 2023-03-24
  • 2016-07-21
相关资源
最近更新 更多