Java check if two rectangles overlap at any point

后端 未结 9 2182
醉梦人生
醉梦人生 2020-11-29 05:12

I have multiple rectangles and one special rectangle: the selection rect. I want to check for each rectangle if the rectangle contains at least one point which is inside the

相关标签:
9条回答
  • 2020-11-29 06:11

    Two rectangles do not overlap if one of the following conditions is true.
    1) One rectangle is above top edge of other rectangle.
    2) One rectangle is on left side of left edge of other rectangle.

    Note that a rectangle can be represented by two coordinates, top left and bottom right. So mainly we are given following four coordinates.
    l1: Top Left coordinate of first rectangle.
    r1: Bottom Right coordinate of first rectangle.
    l2: Top Left coordinate of second rectangle.
    r2: Bottom Right coordinate of second rectangle.

    class Point
    {
        int x, y;
    };
    
    // Returns true if two rectangles (l1, r1) and (l2, r2) overlap
    bool doOverlap(Point l1, Point r1, Point l2, Point r2)
    {
        // If one rectangle is on left side of other
        if (l1.x > r2.x || l2.x > r1.x)
            return false;
    
        // If one rectangle is above other
        if (l1.y < r2.y || l2.y < r1.y)
            return false;
    
        return true;
    }
    
    0 讨论(0)
  • 2020-11-29 06:12

    Background:

    A rectangle can be defined by just one of its diagonal.
    Let's say the first rectangle's diagonal is (x1, y1) to (x2, y2)
    And the other rectangle's diagonal is (x3, y3) to (x4, y4)

    Proceeding:

    Now, if any of these 4 conditions is true, we can conclude that the rectangles are not overlapping:

    1. x3 > x2 (OR)
    2. y3 > y2 (OR)
    3. x1 > x4 (OR)
    4. y1 > y4


    Otherwise, they overlap!

    Alternatively:

    The rectangles overlap if

    (x1 < x4) && (x3 < x2) && (y1 < y4) && (y3 < y2)
    



    Sample solution on Leetcode: https://leetcode.com/problems/rectangle-overlap/discuss/468548/Java-check-if-two-rectangles-overlap-at-any-point

    0 讨论(0)
  • 2020-11-29 06:12

    Here's another simpler solution:

        // Left x 
        int leftX = Math.max(x1, x3);
        // Right x
        int rightX = Math.min(x2, x4);
        // Bottom y
        int botY = Math.max(y1, y3);
        // TopY
        int topY = Math.min(y2, y4);
    
        if (rightX > leftX && topY > botY)
           return true;
    
    0 讨论(0)
提交回复
热议问题