Simple solution with modules for easy understanding


  • 0
    S

    public class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
    int l1 = (int)Math.abs(C - A);
    int b1 = (int)Math.abs(D - B);

        int l2 = (int)Math.abs(G - E);
        int b2 = (int)Math.abs(H - F);
        
        int area = (l1*b1)+(l2*b2);
        if(!isOverlapping(A,B,C,D,E,F,G,H))
        {
            return area;
        }
        
        int commonArea = overlappingArea(A,B,C,D,E,F,G,H);
        
        // since rectangles are overlapping; common area gets considered twice in the calculation areas. 
        return (area -commonArea);
        
    }
    
    private boolean isOverlapping(int A, int B, int C, int D, int E, int F, int G, int H)
    {
        //check x axis
        if(C < E || G < A)
            return false;
            
        // check Y axis
        if(D < F || H < B )
            return false;
        return true;
    }
    
    private int overlappingArea(int A, int B, int C, int D, int E, int F, int G, int H)
    {
        int x1 = A >E ? A: E;
        int x2 = C < G ? C : G;
        
        int y1 = B > F ? B : F;
        int y2 = D < H ? D : H;
        
        int len = (int)Math.abs(x2 - x1);
        int bth = (int)Math.abs(y2 - y1);
        
        return len*bth;
    }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.