[LeetCode] Circle and Rectangle Overlapping

1401. Circle and Rectangle Overlapping

You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle.

Return true if the circle and rectangle are overlapped otherwise return false. In other words, check if there is any point (xi, yi) that belongs to the circle and the rectangle at the same time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
bool intersect(int y1, int x1, int r, int y2, int x2) {
return r * r >= abs(y1 - y2) * abs(y1 - y2) + abs(x1 - x2) * abs(x1 - x2);
}
bool inner(int y, int x, int x1, int y1, int x2, int y2) {
return x1 <= x and x <= x2 and y1 <= y and y <= y2;
}
public:
bool checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) {
if(inner(yCenter, xCenter, x1, y1, x2, y2)) return true;
for(int i = x1; i <= x2; i++) {
if(intersect(yCenter, xCenter, radius, y1, i) or intersect(yCenter, xCenter, radius, y2, i))
return true;
}
for(int i = y1; i <= y2; i++) {
if(intersect(yCenter, xCenter, radius, i, x1) or intersect(yCenter, xCenter, radius, i, x2))
return true;
}
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/20/PS/LeetCode/circle-and-rectangle-overlapping/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.