C++ 中圆形和矩形的重叠


假设我们有一个用 (radius, xc, yc) 表示的圆,其中 (xc, yc) 是圆的中心坐标。我们还有一个用 (x1, y1, x2, y2) 表示的轴对齐矩形,其中 (x1, y1) 是矩形左下角的坐标,(x2, y2) 是矩形右上角的坐标。我们需要检查圆形和矩形是否重叠。

因此,如果输入如下所示:

则输出为 true。

为了解决这个问题,我们将遵循以下步骤:

  • 定义一个函数 eval(),它将接收 a、b、c,

  • 返回 b 和 a 与 c 中最小值的较大值

  • 在主方法中,执行以下操作:

  • cdx := eval(cx, left, right), cdy := eval(cy, bottom, top)

  • rwid := right - left, rh := top - bottom

  • dx := cx - cdx, dy := cy - cdy

  • disSq := (dx * dx) + (dy * dy)

  • sqrRadius := (r * r)

  • 当 disSq <= sqrRadius 时返回 true,否则返回 false

示例

让我们看看下面的实现以更好地理解:

在线演示

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int eval(int a, int b, int c){
      return max(b, min(a, c));
   }
   bool checkOverlap(int r, int cx, int cy, int left, int bottom, int right, int top){
      double cdx = eval(cx, left, right);
      double cdy = eval(cy, bottom, top);
      double rwid = right - left;
      double rh = top - bottom;
      double dx = cx - cdx;
      double dy = cy - cdy;
      double disSq = (dx * dx) + (dy * dy);
      double sqrRadius = (r * r);
      return (disSq <= sqrRadius);
   }
};
main(){
   Solution ob;
   cout << (ob.checkOverlap(1, 0, 0, 1, -1, 3, 1));
}

输入

1, 0, 0, 1, -1, 3, 1

输出

1

更新于:2020年11月17日

303 次浏览

开启你的 职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.