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 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告