Given ‘n’ points on 2-D plane, find the maximum number of points that can be enclosed by a fixed-radius circle of radius ‘R’.
Note: The point is considered to be inside the circle even when it lies on the circumference.
Examples:
Input : R = 1
points[] = {(6.47634, 7.69628), (5.16828 4.79915),
(6.69533 6.20378)}
Output : 2
The maximum number of points are 2
Input : R = 1
points[] = {(6.65128, 5.47490), (6.42743, 6.26189)
(6.35864, 4.61611), (6.59020 4.54228), (4.43967 5.70059)
(4.38226, 5.70536), (5.50755 6.18163), (7.41971 6.13668)
(6.71936, 3.04496), (5.61832, 4.23857), (5.99424, 4.29328)
(5.60961, 4.32998), (6.82242, 5.79683), (5.44693, 3.82724)
(6.70906, 3.65736), (7.89087, 5.68000), (6.23300, 4.59530)
(5.92401, 4.92329), (6.24168, 3.81389), (6.22671, 3.62210)}
Output : 11
The maximum number of points are 11
Naive Algorithm
For an arbitrary pair of points in the given set (say A and B), construct the circles with radius ‘R’ that touches both the points. There are maximum 2 such possible circles. As we can see here maximum possible circles is for CASE 1 i.e. 2.

- For each of the constructed circle, check for each point in the set if it lies inside the circle or not.
- The circle with maximum number of points enclosed is returned.
Time Complexity: There are nC2 pair of points corresponding to which we can have 2nC2 circles at maximum. For each circle, (n-2) points have to be checked. This makes the naive algorithm O(n3).
Angular Sweep Algorithm
By using Angular Sweep, we can solve this problem in O(n2log n). The basic logical idea of this algorithm is described below.
We pick an arbitrary point P from the given set. We then rotate a circle with fixed-radius ‘R’ about the point P. During the entire rotation P lies on the circumference of the circle and we maintain a count of the number of points in the circle at a given value of ? where the parameter ? determines the angle of rotation. The state of a circle can thus be determined by a single parameter ? because the radius is fixed.
We can also see that the value of the count maintained will change only when a point from the set enters or exits the circle.

In the given diagram, C1 is the circle with ? = 0 and C2 is the circle constructed when we rotate the circle at a general value of ?.
After this, the problem reduces to, how to maintain the value of count.
For any given point except P (say Q), we can easily calculate the value of ? for which it enters the circle (Let it be ?) and the value of ? for which it exits the circle (Let it be ?).
We have angles A and B defined as under,
- A is the angle between PQ and the X-Axis.
- B is the angle between PC and PQ where C is the centre of the circle.

where, x and y represent the coordinates of a point and ‘d’ is the distance between P and Q.
Now, from the diagrams we can see that,
? = A-B
? = A+B
(Note: All angles are w.r.t. to X-Axis. Thus, it becomes ‘A-B’ and not ‘B-A’).
When Q enters the circle

When Q exits the circle

We can calculate angles A and B for all points excluding P. Once these angles are found, we sort them and then traverse them in increasing order. Now we maintain a counter which tells us how many points are inside the circle at a particular moment.
Count will change only when a point enters the circle or exits it. In case we find an entry angle we increase the counter by 1 and in case we find an exit angle we decrease the counter by 1. The check that the angle is entry or exit can be easily realised using a flag.
Proceeding like this, the counter always gives us a valid value for the number of points inside the circle in a particular state.
Important Note: The points which have ‘d’>2R do not have to be considered because they will never enter or exit the circle.
The angular sweep algorithm can be described as:
- Calculate the distance between every pair of nC2 points and store them.
- For an arbitrary point (say P), get the maximum number of points that can lie inside the circle rotated about P using the getPointsInside() function.
- The maximum of all values returned will be the final answer.
This algorithm has been described in the following C++ implementation.
CPP
#include <bits/stdc++.h>
using namespace std;
const int MAX_POINTS = 500;
typedef complex< double > Point;
Point arr[MAX_POINTS];
double dis[MAX_POINTS][MAX_POINTS];
bool mycompare(pair< double , bool > A, pair< double , bool > B)
{
if (A.first<B.first)
return true ;
else if (A.first>B.first)
return false ;
else
return (A.second==1);
}
int getPointsInside( int i, double r, int n)
{
vector<pair< double , bool > > angles;
for ( int j=0; j<n; j++)
{
if (i != j && dis[i][j] <= 2*r)
{
double B = acos (dis[i][j]/(2*r));
double A = arg(arr[j]-arr[i]);
double alpha = A-B;
double beta = A+B;
angles.push_back(make_pair(alpha, true ));
angles.push_back(make_pair(beta, false ));
}
}
sort(angles.begin(), angles.end(), mycompare);
int count = 1, res = 1;
vector<pair< double , bool > >::iterator it;
for (it=angles.begin(); it!=angles.end(); ++it)
{
if ((*it).second)
count++;
else
count--;
if (count > res)
res = count;
}
return res;
}
int maxPoints(Point arr[], int n, int r)
{
for ( int i=0; i<n-1; i++)
for ( int j=i+1; j<n; j++)
dis[i][j] = dis[j][i] = abs (arr[i]-arr[j]);
int ans = 0;
for ( int i=0; i<n; i++)
ans = max(ans, getPointsInside(i, r, n));
return ans;
}
int main()
{
Point arr[] = {Point(6.47634, 7.69628),
Point(5.16828, 4.79915),
Point(6.69533, 6.20378)};
int r = 1;
int n = sizeof (arr)/ sizeof (arr[0]);
cout << "The maximum number of points are: "
<< maxPoints(arr, n, r);
return 0;
}
|
Python3
import math
MAX_POINTS = 500
arr = [ 0 ] * MAX_POINTS
dis = [[ 0 for i in range (MAX_POINTS)] for j in range (MAX_POINTS)]
def mycompare(A, B):
if A[ 0 ] < B[ 0 ]:
return True
elif A[ 0 ] > B[ 0 ]:
return False
else :
return A[ 1 ] = = 1
def getPointsInside(i, r, n):
angles = []
for j in range (n):
if i ! = j and dis[i][j] < = 2 * r:
B = math.acos(dis[i][j] / ( 2 * r))
A = math.atan2(arr[j].imag - arr[i].imag, arr[j].real - arr[i].real)
alpha = A - B
beta = A + B
angles.append([alpha, True ])
angles.append([beta, False ])
angles.sort(key = lambda x: (x[ 0 ], x[ 1 ] = = 1 ))
count = 1
res = 1
for angle in angles:
if angle[ 1 ]:
count + = 1
else :
count - = 1
res = max (res, count)
return res
def maxPoints(arr, n, r):
for i in range (n - 1 ):
for j in range (i + 1 , n):
dis[i][j] = dis[j][i] = abs (arr[i] - arr[j])
ans = 0
for i in range (n):
ans = max (ans, getPointsInside(i, r, n))
return ans
r = 1
arr = [ complex ( 6.47634 , 7.69628 ),
complex ( 5.16828 , 4.79915 ),
complex ( 6.69533 , 6.20378 )]
n = len (arr)
print ( "The maximum number of points are:" , maxPoints(arr, n, r))
|
Javascript
const MAX_POINTS = 500;
class Point {
constructor(x, y) {
this .x = x;
this .y = y;
}
subtract(other) {
return new Point( this .x - other.x, this .y - other.y);
}
magnitude() {
return Math.sqrt( this .x * this .x + this .y * this .y);
}
arg() {
return Math.atan2( this .y, this .x);
}
}
const arrPoints = [ new Point(6.47634, 7.69628),
new Point(5.16828, 4.79915),
new Point(6.69533, 6.20378)];
const dis = new Array(MAX_POINTS).fill(0).map(() => new Array(MAX_POINTS).fill(0));
function mycompare(A, B) {
if (A.first < B.first) {
return -1;
} else if (A.first > B.first) {
return 1;
} else {
return A.second == 1 ? -1 : 1;
}
}
function getPointsInside(i, r, n) {
let angles = [];
for (let j = 0; j < n; j++) {
if (i != j && dis[i][j] <= 2 * r) {
let B = Math.acos(dis[i][j] / (2 * r));
let A = arrPoints[j].subtract(arrPoints[i]).arg();
let alpha = A - B;
let beta = A + B;
angles.push([alpha, true ]);
angles.push([beta, false ]);
}
}
angles.sort(mycompare);
let count = 1;
let res = 1;
for (let i = 0; i < angles.length; i++) {
if (angles[i][1]) {
count++;
}
else {
count--;
}
if (count > res) {
res = count;
}
}
return res;
}
function maxPoints(arrPoints, n, r) {
for (let i = 0; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
dis[i][j] = dis[j][i] = arrPoints[i].subtract(arrPoints[j]).magnitude();
}
}
let ans = 0;
for (let i = 0; i < n; i++) {
ans = Math.max(ans, getPointsInside(i, r, n));
}
return ans;
}
const n = arrPoints.length;
const r = 1;
console.log(`The maximum number of points are: ${maxPoints(arrPoints, n, r)}`);
|
Output:
The maximum number of points are: 2
Time Complexity: There are n points for which we call the function getPointsInside(). This function works on ‘n-1’ points for which we get 2*(n-1) size of the vector ‘angles’ (one entry angle and one exit angle). Now this ‘angles’ vector is sorted and traversed which gives complexity of the getPointsInside() function equal to O(nlogn). This makes the Angular Sweep Algorithm O(n2log n).
Space complexity: O(n) since using auxiliary space for vector
Related Resources: Using the complex class available in stl for implementing solutions to geometry problems.
http://codeforces.com/blog/entry/22175
This article is contributed by Aanya Jindal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.