Check if any point overlaps the given Circle and Rectangle
Given two opposite diagonal points of a rectangle (X1, Y1), (X2, Y2) and the center, radius of the circle R, (Xc, Yc), the task is to check if there exists any point P that belongs to both the circle as well as the rectangle.
Input: R = 2, Xc = 0, Yc = 0, X1 = 1, Y1 = 0, X2 = 3, Y2 = 3
Clearly, from the below illustration, the circle and the rectangle intersect.
Attention reader! All those who say programming isn't for kids, just haven't met the right mentors yet. Join the Demo Class for First Step to Coding Course, specifically designed for students of class 8 to 12.
The students will get to learn more about the world of programming in these free classes which will definitely help them in making a wise career choice in the future.
Input: R = 1, Xc = 1, Yc = 1, X1 = 3, Y1 = 3, X2 = 5, Y2 = 6
Approach: The idea is to simply check if the circle and the rectangle intersect or not. There are essentially 2 possible cases when the intersection occurs.
- Case 1: The side of the rectangle touches or intersects the circle. In order to check whether the shapes intersect, we need to find a point on or inside the rectangle that is closest to the center of the circle. If this point lies on or inside the circle, it is guaranteed that both the shapes intersect. Let the closest point be denoted by (Xn, Yn). Then the distance between the closest point and the center of the circle can be found using sqrt((Xc- Xn)2 + (Yc- Yn)2). If this distance ≤ the radius of the circle, the two shapes intersect.
- Case 2: The center of the circle lies inside the rectangle. Since the center of the circle lies inside the rectangle, the closest point will be (Xc, Yc).
On close observation, it can be observed that the point of interest only depends on the locations of (X1, Y1) and (X2, Y2) relative to (Xc, Yc). Therefore, the closest point in both the above cases can be calculated as:
- Xn= max(X1, min(Xc, X2))
- Yn= max(Y1, min(Yc, Y2))
Below is the implementation of the above approach:
Time Complexity: O(1)
Auxiliary Space: O(1)