在 C++ 中查找至少有一个点在其上方、下方、左侧或右侧的点的数量


在这个问题中,我们得到了位于二维平面上的 N 个点。我们的任务是 *查找至少有一个点在其上方、下方、左侧或右侧的点的数量*。

我们需要计算所有至少有一个点满足以下任何条件的点。

**在其上方的点** - 该点将具有相同的 X 坐标,并且 Y 坐标比其当前值多一。

**在其下方的点** - 该点将具有相同的 X 坐标,并且 Y 坐标比其当前值少一。

**在其左侧的点** - 该点将具有相同的 Y 坐标,并且 X 坐标比其当前值少一。

**在其右侧的点** - 该点将具有相同的 Y 坐标,并且 X 坐标比其当前值多一。

让我们来看一个例子来理解这个问题:

Input : arr[] = {{1, 1}, {1, 0}, {0, 1}, {1, 2}, {2, 1}}
Output :1

解决方案方法

为了解决这个问题,我们需要从平面上获取每个点,并找到其相邻点可以具有的 X 和 Y 坐标的最大值和最小值,以进行有效计数。如果存在任何坐标具有相同的 X 坐标并且 Y 值在范围内,我们将增加点数。我们将计数存储在一个变量中并返回它。

示例

让我们来看一个例子来理解这个问题

#include <bits/stdc++.h>
using namespace std;
#define MX 2001
#define OFF 1000
struct point {
   int x, y;
};
int findPointCount(int n, struct point points[]){
   int minX[MX];
   int minY[MX];
   int maxX[MX] = { 0 };
   int maxY[MX] = { 0 };
   int xCoor, yCoor;
   fill(minX, minX + MX, INT_MAX);
   fill(minY, minY + MX, INT_MAX);
   for (int i = 0; i < n; i++) {
      points[i].x += OFF;
      points[i].y += OFF;
      xCoor = points[i].x;
      yCoor = points[i].y;
      minX[yCoor] = min(minX[yCoor], xCoor);
      maxX[yCoor] = max(maxX[yCoor], xCoor);
      minY[xCoor] = min(minY[xCoor], yCoor);
      maxY[xCoor] = max(maxY[xCoor], yCoor);
   }
   int pointCount = 0;
   for (int i = 0; i < n; i++) {
      xCoor = points[i].x;
      yCoor = points[i].y;
      if (xCoor > minX[yCoor] && xCoor < maxX[yCoor])
         if (yCoor > minY[xCoor] && yCoor < maxY[xCoor])
            pointCount++;
   }
   return pointCount;
}
int main(){
   struct point points[] = {{1, 1}, {1, 0}, {0, 1}, {1, 2}, {2, 1}};
   int n = sizeof(points) / sizeof(points[0]);
   cout<<"The number of points that have atleast one point above, below, left, right is "<<findPointCount(n, points);
}

输出

The number of points that have atleast one point above, below, left, right is 1

更新于:2022年1月24日

81 次浏览

开启你的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.