在 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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP