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 trueif the circle and rectangle are overlapped otherwise returnfalse. In other words, check if there is any point (xi, yi) that belongs to the circle and the rectangle at the same time.
The closest point on the rectangle to the circle’s center determines the minimum distance between the circle and the rectangle. If this distance is less than or equal to the radius, the circle and rectangle overlap.
classSolution {
public:bool checkOverlap(int r, int xc, int yc, int x1, int y1, int x2, int y2) {
int x = max(x1, min(xc, x2));
int y = max(y1, min(yc, y2));
int dx = x - xc, dy = y - yc;
return dx * dx + dy * dy <= r * r;
}
};
classSolution {
publicbooleancheckOverlap(int r, int xc, int yc, int x1, int y1, int x2, int y2) {
int x = Math.max(x1, Math.min(xc, x2));
int y = Math.max(y1, Math.min(yc, y2));
int dx = x - xc, dy = y - yc;
return dx * dx + dy * dy <= r * r;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funcheckOverlap(r: Int, xc: Int, yc: Int, x1: Int, y1: Int, x2: Int, y2: Int): Boolean {
val x = xc.coerceIn(x1, x2)
val y = yc.coerceIn(y1, y2)
val dx = x - xc
val dy = y - yc
return dx * dx + dy * dy <= r * r
}
}
1
2
3
4
5
6
classSolution:
defcheckOverlap(self, r: int, xc: int, yc: int, x1: int, y1: int, x2: int, y2: int) -> bool:
x = min(max(xc, x1), x2)
y = min(max(yc, y1), y2)
dx, dy = x - xc, y - yc
return dx * dx + dy * dy <= r * r
1
2
3
4
5
6
7
8
9
impl Solution {
pubfncheck_overlap(r: i32, xc: i32, yc: i32, x1: i32, y1: i32, x2: i32, y2: i32) -> bool {
let x = xc.max(x1).min(x2);
let y = yc.max(y1).min(y2);
let dx = x - xc;
let dy = y - yc;
dx * dx + dy * dy <= r * r
}
}