leetcode Question: Rectangle Area

Rectangle Area

Find the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
Rectangle Area
Assume that the total area is never beyond the maximum possible value of int.

Analysis:


There are two step for solving this problem:
1. Check if the two rectangles are overlap or not.
2. Compute the overlap area. The overall area is \(area_1 + area_2 - area_{overlap}\).

To check the overlap of two rectangles, consider the non-overlap conditions:
1. A is on the left of B.  (A's right edge is on the left of B's left edge)
2. A is on the right of B.  (A's left edge is on the right of B's right edge)
3. A is on top of B.  (A's bottom edge is on top of B's top edge)
4. A is on the bottom of B.  (A's top edge is on the bottom of B's bottom edge)
In this problem:
Conditions A>G, C<E, D<F, B>H are corresponding to the above 4 conditions to check if the two rectangles are overlap.

To compute the overlap area, according to the figure in the question, it is not hard to derive the area is: \((\min(D, H) - \max(B,F)) \times (\min(C,G)-\max(A,E))\).




Code(C++):


class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int area = (C-A)*(D-B) + (G-E)*(H-F);
        if (A>G || C < E || D < F || B > H){
            return area;
        } else{
            return area - (min(D, H)- max(B, F))*(min(C,G)- max(A,E));
        }
    }
};


Code(Python):


class Solution(object):
    def computeArea(self, A, B, C, D, E, F, G, H):
        """
        :type A: int
        :type B: int
        :type C: int
        :type D: int
        :type E: int
        :type F: int
        :type G: int
        :type H: int
        :rtype: int
        """
        area = (C-A)*(D-B) + (G-E)*(H-F)
        if A > G or C < E or D < F or B > H: 
            return area
        else:
            return area - (min(D, H)- max(B, F))*(min(C,G)- max(A,E))


No comments:

Post a Comment