To solve the problem of finding the area of intersection between two axis-aligned rectangles, follow these steps:
Approach
The key insight is to determine the boundaries of the overlapping region (if it exists) between the two rectangles:
- Overlap Boundaries:
- The left boundary of the intersection is the maximum of the left edges of both rectangles.
- The right boundary is the minimum of the right edges.
- The bottom boundary is the maximum of the bottom edges.
- The top boundary is the minimum of the top edges.
- Check Validity: If the computed width (right-left) or height (top-bottom) of the overlap is non-positive, there is no intersection (area = 0). Otherwise, the area is the product of width and height.
Solution Code
# Read coordinates of the two rectangles
x1, y1, x2, y2 = map(int, input().split())
x3, y3, x4, y4 = map(int, input().split())
# Calculate overlapping region boundaries
overlap_left = max(x1, x3)
overlap_right = min(x2, x4)
overlap_bottom = max(y1, y3)
overlap_top = min(y2, y4)
# Compute width and height of the overlap
width = overlap_right - overlap_left
height = overlap_top - overlap_bottom
# Calculate area if overlap exists
area = width * height if (width > 0 and height > 0) else 0
print(area)
Explanation
- Input Handling: The code reads the coordinates of two rectangles (each defined by 4 integers: bottom-left (x,y) and top-right (x,y)).
- Overlap Calculation: The overlapping region is determined by taking the maximum of left edges (to get the start of the overlap) and the minimum of right edges (to get the end of the overlap), similarly for vertical edges.
- Area Calculation: If the overlap dimensions are positive, the area is their product; otherwise, it's zero (no intersection).
This approach efficiently computes the intersection area in constant time (O(1)) since it involves basic arithmetic operations. It works for all axis-aligned rectangles, regardless of their position relative to each other.
Example:
If the input is:
0 0 2 2
1 1 3 3
The output is: 1 (overlap is from (1,1) to (2,2), area = (2-1)*(2-1) =1).
Another example:
0 0 1 1
2 2 3 3
Output:0 (no overlap).
This solution is optimal and directly addresses the problem of finding the intersection area of two rectangles.


作者声明:本文包含人工智能生成内容。