矩形盒装箱算法:拟合矩形

问题描述 投票:0回答:1

我正在解决一个问题,涉及对矩形执行两种类型的操作。这些操作表示为一个数组,其中每个操作可以是以下两种类型之一:

[0, a, b] - 此操作创建并保存尺寸为 a × b 的矩形。

[1, a, b] - 此操作检查所有先前保存的矩形是否可以放入尺寸为 a × b 的盒子内。需要注意的是,矩形可以旋转 90 度,这意味着尺寸为 b × a 的矩形被认为等同于尺寸为 a × b 的矩形。

我的代码旨在确定是否可以满足每个“1”类型操作,并且它似乎对于大多数测试用例都适用。然而,有一个测试用例失败了,我正在努力找出错误。你能帮我找出错误吗?

这是我当前的解决方案:

def solution(operations):
    res = []
    maxWidth = maxHeight = 0
    
    for t, a, b in operations:
        if t == 0:
            maxWidth = max(maxWidth, a)
            maxHeight = max(maxHeight, b)
            
        else:
            fits = (maxWidth <= a and maxHeight <= b or maxHeight <= a and maxWidth <= b)
            res.append(fits)

    return res
python algorithm optimization geometry
1个回答
0
投票

将 maxWidth 和 maxHeight 与 a 和 b 进行比较,以便考虑旋转

def solution(operations):
    res = []
    maxWidth = maxHeight = 0
    
    for t, a, b in operations:
        if t == 0:
            maxWidth = max(maxWidth, a)
            maxHeight = max(maxHeight, b)
            
        else:
            # Check if both max dimensions can fit within box dimensions a x b
            fits = (maxWidth <= a and maxHeight <= b) or (maxWidth <= b and maxHeight <= a)
            res.append(fits)

    return res
© www.soinside.com 2019 - 2024. All rights reserved.