Leetcode 223. Rectangle Area

Problem

Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.

The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2).

The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2).

Algorithm

Divide the region into 9 parts with the corners and then deal with them by the ids.
Leetcode 223. Rectangle Area_第1张图片

Code

class Solution:
    def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
        y1 = 0
        if by1 <= ay1:
            y1 = 0
        elif by1 <= ay2:
            y1 = 1
        else:
            y1 = 2

        x1 = 0
        if bx1 < ax1:
            x1 = 1
        elif bx1 <= ax2:
            x1 = 2
        else:
            x1 = 3

        id1 = y1 * 3 + x1

        y2 = 0
        if by2 <= ay1:
            y2 = 0
        elif by2 <= ay2:
            y2 = 1
        else:
            y2 = 2

        x2 = 0
        if bx2 < ax1:
            x2 = 1
        elif bx2 <= ax2:
            x2 = 2
        else:
            x2 = 3

        id2 = y2 * 3 + x2

        print(id1, id2)
        overlap = 0
        if id2 == 5 or id2 == 6 or id2 == 8 or id2 == 9:
            xx2 = min(ax2, bx2)
            yy2 = min(ay2, by2)
            if id1 == 1:
                xx1 = ax1
                yy1 = ay1
            elif id1 == 2:
                xx1 = bx1
                yy1 = ay1
            elif id1 == 4:
                xx1 = ax1
                yy1 = by1
            elif id1 == 5:
                xx1 = bx1
                yy1 = by1
            else:
                xx1 = xx2
                yy1 = yy2
            overlap = (xx2 - xx1) * (yy2 - yy1)
        
        return (ax2 - ax1) * (ay2 - ay1) + (bx2 - bx1) * (by2 - by1) - overlap

你可能感兴趣的:(Leetcode,入门题,解题报告,leetcode,算法,职场和发展)