zoukankan      html  css  js  c++  java
  • [LeetCode#223]Rectangle Area

    Problem:

    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:

    The seems complex problem could be easily analyzed and sovled through simple analysis. 
    If you try to analyze and distinguish in the scope of rectangle, it is too crazy to clear the relationship between them. 
    
    But we could actually do it in a very simple way. We analyze the prolem through two separate direction: vertical direction and horizontal direction.
    Principle: Once rectangle A in connected rectangle B, there must be a overlay either in vertical direction or horizontal direction. Otherwise they could not overlay with each other. 
    
    The horizontal direction:
    A-------------------- C
    
            E--------------------------G
            
            
    E-------------------- G
            A------------------------C
    
    If the two rectangles overlay with each other, at horizontal direction, it must meet one the above situation.
    If not, they are not overlay.
            if (A > G || C < E)
                return (H-F)*(G-E) + (D-B)*(C-A);
    
    We could also see that, since A is the left edge of C, E is the left edge of G,
    The left coordinate for the overlaied rectangles is :
    ---------------------------------------------------
    int left = Math.max(A, E);
    The right coordinate for the overlaied rectangles is :
    -------------------------------------------------------
    int right = Math.min(C, G);
    
    The same analysis could apply to the vertical direction.
    
    Skill:
    To compute the overall area, we could use: total area - overlaid area.

    Solution:

    public class Solution {
        public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
            if (A > G || C < E)
                return (H-F)*(G-E) + (D-B)*(C-A);
            if (B > H || D < F)
                return (H-F)*(G-E) + (D-B)*(C-A);
            int left = Math.max(A, E);
            int right = Math.min(C, G);
            int bottom = Math.max(B, F);
            int top = Math.min(D, H);
            return (H-F)*(G-E) + (D-B)*(C-A) - (top-bottom)*(right-left);
        }
    }
  • 相关阅读:
    【AtCoder】ARC097 (C
    【51nod】1123 X^A Mod B (任意模数的K次剩余)
    【洛谷】P4207 [NOI2005]月下柠檬树
    【POJ】2454.Jersey Politics
    【POJ】2069.Super Star
    【POJ】2420.A Star not a Tree?(模拟退火)
    【POJ】1026.Cipher
    【POJ】3270.Cow Sorting
    【POJ】1286.Necklace of Beads
    【POJ】1067.取石子游戏
  • 原文地址:https://www.cnblogs.com/airwindow/p/4768348.html
Copyright © 2011-2022 走看看