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);
        }
    }
  • 相关阅读:
    DELPHI中应用GoogleMap[转]
    给DBGrid添加鼠标滚动事件
    枚举和卸载消息钩子[转]
    区域性名称和标识符
    VCL 中的 Windows API 函数: AlphaBlend
    高效读书,实用阅读指南
    defaultservlethandler不生效原因,springmvc静态资源拦截方案比较
    indexOf原理,Java,javascript,python实现
    可见性是什么?(通俗易懂)
    我们一起学程序五子棋
  • 原文地址:https://www.cnblogs.com/airwindow/p/4768348.html
Copyright © 2011-2022 走看看