How to determine whether two axis‑aligned rectangles overlap in Python

1 Answer

0 votes
# 
# Axis‑aligned rectangles are simply rectangles whose edges are parallel to the 
# coordinate axes — meaning their sides are horizontal and vertical. 
# That single assumption makes the overlap test dramatically simpler and faster.
#

#
#    Rectangle overlap detection (axis-aligned)
#
#    Each rectangle is defined by:
#        - x, y : coordinates of its top-left corner
#        - w, h : width and height
#
#    Two rectangles DO NOT overlap if any separating condition is true:
#        - One is completely to the left of the other
#        - One is completely to the right of the other
#        - One is completely above the other
#        - One is completely below the other
#
#    Otherwise, they overlap.
#
#    This is the standard O(1) test for axis-aligned rectangles.
#

class Rect:
    def __init__(self, x, y, w, h):
        self.x = x      # top-left X
        self.y = y      # top-left Y
        self.w = w      # width
        self.h = h      # height

#
#    Returns true if rectangles A and B overlap.
#
def rectanglesOverlap(A, B):
    # Compute edges of A
    A_left   = A.x
    A_right  = A.x + A.w
    A_top    = A.y
    A_bottom = A.y + A.h

    # Compute edges of B
    B_left   = B.x
    B_right  = B.x + B.w
    B_top    = B.y
    B_bottom = B.y + B.h

    # Separating conditions:
    if A_right <= B_left:   return False   # A is left of B
    if B_right <= A_left:   return False   # B is left of A
    if A_bottom <= B_top:   return False   # A is above B
    if B_bottom <= A_top:   return False   # B is above A

    return True  # Otherwise, they overlap

# Example rectangles
A = Rect(10, 10, 30, 20)   # Example rectangle A
B = Rect(25, 15, 40, 25)   # Overlaps A
C = Rect(100, 100, 10, 10) # Does not overlap A

print("A vs B overlap? " + ("YES" if rectanglesOverlap(A, B) else "NO"))
print("A vs C overlap? " + ("YES" if rectanglesOverlap(A, C) else "NO"))



#
# run:
#
# A vs B overlap? YES
# A vs C overlap? NO
#

 



answered Jul 18 by avibootz

Related questions

...