
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Number of Points with Neighboring Points in C++
In this problem, we are given N points that lie in a 2D plane. Our task is to find the number of points that have at least 1 point above, below, left or right of it.
We need to count all the points that have at least 1 point which satisfies any of the below conditions.
Point above it − The point will have the same X coordinate and the Y coordinate is one more than its current value.
Point below it − The point will have the same X coordinate and the Y coordinate is one less than its current value.
Point left of it − The point will have the same Y coordinate and the X coordinate is one less than its current value.
Point right of it − The point will have the same Y coordinate and the X coordinate is one more than its current value.
Let’s take an example to understand the problem,
Input : arr[] = {{1, 1}, {1, 0}, {0, 1}, {1, 2}, {2, 1}} Output :1
Solution Approach
To solve the problem, we need to take each point form the plane and find the maximum and minimum value of X and Y coordinates its neighbours points can have for a valid count. And if any coordinate exists that has the same X coordinate and Y’s value lies in the range. We will increase point count. We will store the count in a variable and return it.
Example
Let’s take an example to understand the problem
#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); }
Output
The number of points that have atleast one point above, below, left, right is 1