How to check if two rectangles intersect or not ?



How to check if two rectangles intersect or not ?

    • The following standard Java coding practices to solve this problem.
    • We have an encapsulated two co-ordinates in a Point class and have Rectangle has two Point instance variable and an instance method like equals() to check if another rectangle is overlapping or not.
    •  To Check Rectangle Intersects or Not

      To Check Rectangle Intersects or Not

    • A rectangle can be represented by two coordinates, top left, and bottom right. As part of the problem you will be given four coordinates L1, R1 and L2, R2, top left and bottom right coordinate of two rectangles and you need to write a function isOverlapping() which should return true if rectangles are overlapping or false if they are not.

    Read Also

    Sample Code in Java:

      public class Main {
      
        public static void main(String[] args) {
        Point l1 = new Point(0, 10);
        Point r1 = new Point(10, 0);
        Point l2 = new Point(5, 5);
        Point r2 = new Point(15, 0);
      
        Rectangle first = new Rectangle(l1, r1);
        Rectangle second = new Rectangle(l2, r2);
      
        if (first.isOverLapping(second)) {
        System.out
        .println("Yes, two rectangles are intersecting with each other");
        } else {
        System.out
        .println("No, two rectangles are not overlapping with each other");
        }
        }
      
      }
      
      class Point {
        int x;
        int y;
      
        public Point(int x, int y) {
        super();
        this.x = x;
        this.y = y;
        }
      }
      
      class Rectangle {
      
        private final Point topLeft;
        private final Point bottomRight;
      
        public Rectangle(Point topLeft, Point bottomRight) {
        this.topLeft = topLeft;
        this.bottomRight = bottomRight;
        }
      
        public boolean isOverLapping(Rectangle other) {
        if (this.topLeft.x > other.bottomRight.x // R1 is right to R2
        || this.bottomRight.x < other.topLeft.x // R1 is left to R2
        || this.topLeft.y < other.bottomRight.y // R1 is above R2
        || this.bottomRight.y > other.topLeft.y) { // R1 is below R1
        return false;
        }
        return true;
        }
      
      }
      

      Output

        Yes, two rectangles are intersecting with each other
        


        Related Searches to How to check if two rectangles intersect or not ?