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.
To deal with various cases, analyze the length and width of intersecting graphs, and calculate the area.
Class Solution {public: int computearea (int A, int B, int C, int D, int E, int F, int G, int H) { int l1 = 0; int l2 = 0; if (a<=e&&g<=c) L1 = g-e; if (a<=e&&e<=c&&c<=g) L1 = c-e; if (e<=a&&a<=g&&g<=c) L1 = g-a; if (e<=a&&c<=g) L1 = c-a; if (b<=f&&h<=d) L2 = h-f; if (b<=f&&f<=d&&d<=h) L2 = d-f; if (f<=b&&b<=h&&h<=d) L2 = h-b; if (f<=b&&d<=h) L2 = d-b; Return (C-A) * (d-b) + (G-E) * (h-f)-l1*l2; };
This code is too redundant to actually intersect two segments, which is the minimum value of the first two points and the maximum of the last two points. can be resolved with one line of code.
Class Solution {public: int computearea (int A, int B, int C, int D, int E, int F, int G, int H) { return (c-a) * (d B) + (G-E) * (h-f)-max (0,min (c,g)-max (e,a)) *max (0,min (d,h)-max (f,b)); }};
[Leetcode] Rectangle Area