Determine if two rectangles overlap each other?

前端 未结 23 827
礼貌的吻别
礼貌的吻别 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 05:05
    struct point { int x, y; };
    
    struct rect { point tl, br; }; // top left and bottom right points
    
    // return true if rectangles overlap
    bool overlap(const rect &a, const rect &b)
    {
        return a.tl.x <= b.br.x && a.br.x >= b.tl.x && 
               a.tl.y >= b.br.y && a.br.y <= b.tl.y;
    }
    
    0 讨论(0)
  • 2020-11-22 05:10
    struct Rect
    {
        Rect(int x1, int x2, int y1, int y2)
        : x1(x1), x2(x2), y1(y1), y2(y2)
        {
            assert(x1 < x2);
            assert(y1 < y2);
        }
    
        int x1, x2, y1, y2;
    };
    
    bool
    overlap(const Rect &r1, const Rect &r2)
    {
        // The rectangles don't overlap if
        // one rectangle's minimum in some dimension 
        // is greater than the other's maximum in
        // that dimension.
    
        bool noOverlap = r1.x1 > r2.x2 ||
                         r2.x1 > r1.x2 ||
                         r1.y1 > r2.y2 ||
                         r2.y1 > r1.y2;
    
        return !noOverlap;
    }
    
    0 讨论(0)
  • 2020-11-22 05:10

    Here's how it's done in the Java API:

    public boolean intersects(Rectangle r) {
        int tw = this.width;
        int th = this.height;
        int rw = r.width;
        int rh = r.height;
        if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {
            return false;
        }
        int tx = this.x;
        int ty = this.y;
        int rx = r.x;
        int ry = r.y;
        rw += rx;
        rh += ry;
        tw += tx;
        th += ty;
        //      overflow || intersect
        return ((rw < rx || rw > tx) &&
                (rh < ry || rh > ty) &&
                (tw < tx || tw > rx) &&
                (th < ty || th > ry));
    }
    
    0 讨论(0)
  • 2020-11-22 05:10

    Don't think of coordinates as indicating where pixels are. Think of them as being between the pixels. That way, the area of a 2x2 rectangle should be 4, not 9.

    bool bOverlap = !((A.Left >= B.Right || B.Left >= A.Right)
                   && (A.Bottom >= B.Top || B.Bottom >= A.Top));
    
    0 讨论(0)
  • 2020-11-22 05:11

    If the rectangles overlap then the overlap area will be greater than zero. Now let us find the overlap area:

    If they overlap then the left edge of overlap-rect will be the max(r1.x1, r2.x1) and right edge will be min(r1.x2, r2.x2). So the length of the overlap will be min(r1.x2, r2.x2) - max(r1.x1, r2.x1)

    So the area will be:

    area = (max(r1.x1, r2.x1) - min(r1.x2, r2.x2)) * (max(r1.y1, r2.y1) - min(r1.y2, r2.y2))
    

    If area = 0 then they don't overlap.

    Simple isn't it?

    0 讨论(0)
提交回复
热议问题