计算几何-5361. 圆和矩形是否有重叠

2020-04-05 09:22:15

问题描述:

给你一个以 (radius, x_center, y_center) 表示的圆和一个与坐标轴平行的矩形 (x1, y1, x2, y2),其中 (x1, y1) 是矩形左下角的坐标,(x2, y2) 是右上角的坐标。

如果圆和矩形有重叠的部分,请你返回 True ,否则返回 False 。

换句话说,请你检测是否 存在 点 (xi, yi) ,它既在圆上也在矩形上(两者都包括点落在边界上的情况)。 

示例 1:

输入:radius = 1, x_center = 0, y_center = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1
输出:true
解释:圆和矩形有公共点 (1,0) 

示例 2:

输入:radius = 1, x_center = 0, y_center = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1
输出:true

提示:

扫描二维码关注公众号,回复: 10491664 查看本文章

1 <= radius <= 2000
-10^4 <= x_center, y_center, x1, y1, x2, y2 <= 10^4
x1 < x2
y1 < y2

问题求解:

寻找矩形中离圆心最近的点,再比较距离即可。

    public boolean checkOverlap(int radius, int x, int y, int x1, int y1, int x2, int y2) {
        int yy = (y <= y2 && y >= y1) ? 0 : Math.min(Math.abs(y1 - y), Math.abs(y2 - y));
        int xx = (x >= x1 && x <= x2) ? 0 : Math.min(Math.abs(x1 - x), Math.abs(x2 - x));
        return xx * xx + yy * yy <= radius * radius;
    }

  

猜你喜欢

转载自www.cnblogs.com/hyserendipity/p/12635877.html
今日推荐