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);
        }
    }
  • 相关阅读:
    中国内地、台湾、香港、澳门和国外DNS服务器地址列表
    科学、道法、哲学
    Away 3d 基本属性
    away 3d的一些问题
    Adobe Flash CC 2014 下载及破解
    html5结合flash实现视频文件在所有主流浏览器兼容播放
    Html wmode 标签参数详解
    九宫格
    flash/flex 编译错误汇总
    Redis在windows下安装过程(转)
  • 原文地址:https://www.cnblogs.com/airwindow/p/4768348.html
Copyright © 2011-2022 走看看