My concise 0ms C Solution with explanation


  • -1
    Z
    int dist(int x, int y){
        return x - y > 0 ? x - y : y - x;
    }
    /*
    0. Only (A,B) inside EFGH: 
    area -= (G - A) * (H - B);
    1. Only (A,B), (A,D) inside EFGH
    area -= (G - A) * (D - B);
    2. Only (A,B), (C,B) inside EFGH
    area -= (C - A) * (H - B);
    3. ABCD inside EFGH
    area -= (C - A) * (D - B);
    */
    
    #define Compare(area,A,B,C,D,E,F,G,H)\
    if((A >= E && A <= G || A <= E && A >= G )&&(B >= F && B <= H || B <= F && B >= H)){\
        int ca = dist(C,A);\
        int ga = dist(G,A);\
        int db = dist(D,B);\
        int hb = dist(H,B);\
        return area - (ca < ga ? ca : ga) * (db < hb ? db: hb);\
    }
    
    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);
    
        Compare(area,A,B,C,D,E,F,G,H);
        Compare(area,C,B,A,D,G,F,E,H);
        Compare(area,C,D,A,B,G,H,E,F);
        Compare(area,A,D,C,B,E,H,G,F);
    
        Compare(area,E,F,G,H,A,B,C,D);
        Compare(area,G,F,E,H,C,B,A,D);
        Compare(area,G,H,E,F,C,D,A,B);
        Compare(area,E,H,G,F,A,D,C,B);
    
        // non-overlap
        return area;
    }

Log in to reply
 

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