Topic links
https://leetcode.com/problems/rectangle-area/
Original title
Find the total area covered by and rectilinear rectangles in a 2D plane.
Each rectangle was defined by its bottom left corner and top right corner as shown in the figure.
Assume the total area is never beyond the maximum possible value of int.
Topic translation
Find the total area covered by two 2-D rectangles. Each rectangle is defined by the lower-left and upper-right coordinates, as shown in the overlay (pictured above). Assume that the total area of coverage does not exceed the maximum value of type int.
Method of Thinking
The area of the overlapping portion is reduced by the area of the two rectangles respectively. So the point is to determine whether the two rectangles overlap, and the area of the overlapping parts.
The area of overlap is divided into two steps: to find the width and height, but also to pay attention to the negative situation when not overlapping.
Idea one
Decide whether to overlap, and then return the results accordingly.
Code
class solution(object): def Computearea(self, A, B, C, D, E, F, G, H): "" " : Type A:int:type b:int:type c:int:type d:int:type e:int:type F : Int:type g:int:type h:int:rtype:int "" " ifB>=horE>=corF>=dorA>=g:return(c-a) * (d-b) + (G-E) * (h-f) width = min (c,g)-Max (a,e) height = min (d,h)-Max (B,F)return(c-a) * (d-b) + (G-E) * (h-f)-Width * height
Idea two
Calculates the area of overlapping portions directly, with zero length or width when not overlapped.
Code One
class Solution(object): def computeArea(self, A, B, C, D, E, F, G, H): """ :type A: int :type B: int :type C: int :type D: int :type E: int :type F: int :type G: int :type H: int :rtype: int """ width = max(0, min(C,G) - max(A,E)) height = max(0, min(D,H) - max(B,F)) return (C-A) * (D-B) + (G-E) * (H-F) - width * height
Description
The same idea, but the lower left and upper right coordinates of the overlapping rectangles may be better understood.
Code two
class solution (object) : def computearea : left = max (a,e) right = Max (min (c,g), left) bottom = Max (b,f) top = max (min (d,h), bottom) return (c-a) * (d-b) + (G-E) * (H-F) -(Right-left) * (top-bottom)
PS: Novice Brush Leetcode, new handwritten blog, write wrong or write not clear also please help point out, thank you!
Reprint Please specify: http://blog.csdn.net/coder_orz/article/details/51679907
223. Rectangle area [Easy] (Python)