Determine if two rectangles overlap each other?

前端 未结 23 1202
礼貌的吻别
礼貌的吻别 2020-11-22 04:09

I am trying to write a C++ program that takes the following inputs from the user to construct rectangles (between 2 and 5): height, width, x-pos, y-pos. All of these rectang

23条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 04:59

    Ask yourself the opposite question: How can I determine if two rectangles do not intersect at all? Obviously, a rectangle A completely to the left of rectangle B does not intersect. Also if A is completely to the right. And similarly if A is completely above B or completely below B. In any other case A and B intersect.

    What follows may have bugs, but I am pretty confident about the algorithm:

    struct Rectangle { int x; int y; int width; int height; };
    
    bool is_left_of(Rectangle const & a, Rectangle const & b) {
       if (a.x + a.width <= b.x) return true;
       return false;
    }
    bool is_right_of(Rectangle const & a, Rectangle const & b) {
       return is_left_of(b, a);
    }
    
    bool not_intersect( Rectangle const & a, Rectangle const & b) {
       if (is_left_of(a, b)) return true;
       if (is_right_of(a, b)) return true;
       // Do the same for top/bottom...
     }
    
    bool intersect(Rectangle const & a, Rectangle const & b) {
      return !not_intersect(a, b);
    }
    

提交回复
热议问题