Leetcode 223. Rectangle Area

285 篇文章 2 订阅
130 篇文章 0 订阅

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.
在这里插入图片描述

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值