total area of intersecting rectangles

前端 未结 6 1237
余生分开走
余生分开走 2020-12-23 09:43

I need an algorithm to solve this problem: Given 2 rectangles intersecting or overlapping together in any corner, how do I determine the total area for the two rectangles wi

6条回答
  •  臣服心动
    2020-12-23 10:40

    Here is complete solution for this algorithm using Java:

    public static int solution(int K, int L, int M, int N, int P, int Q, int R,
            int S) {
        int left = Math.max(K, P);
        int right = Math.min(M, R);
        int bottom = Math.max(L, Q);
        int top = Math.min(N, S);
    
        if (left < right && bottom < top) {
            int interSection = (right - left) * (top - bottom);
            int unionArea = ((M - K) * (N - L)) + ((R - P) * (S - Q))
                    - interSection;
            return unionArea;
        }
        return 0;
    } 
    

提交回复
热议问题