You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断两个矩形是否重叠?求可实现该功能的伪代码

判断矩形重叠的伪代码实现

Alright, let's break down how to check if two rectangles overlap. The key insight here is to first check when the rectangles don't overlap—then we just reverse that logic to find when they do.

核心逻辑

Two rectangles do NOT overlap if one of these four conditions is true:

  • Rectangle 1 is completely to the left of Rectangle 2
  • Rectangle 1 is completely to the right of Rectangle 2
  • Rectangle 1 is completely below Rectangle 2
  • Rectangle 1 is completely above Rectangle 2

If none of these are true, the rectangles must overlap.

伪代码实现

First, let's define each rectangle with its boundary values:

  • For any rectangle rect, rect.x1 = left boundary, rect.x2 = right boundary (where x1 < x2)
  • rect.y1 = bottom boundary, rect.y2 = top boundary (where y1 < y2)

Here's the function to check overlap:

// Define the two rectangles from your problem
rect1 = {
    x1: 0.0,
    x2: 1.0,
    y1: 0.0,
    y2: 1.0
}

rect2 = {
    x1: 0.7,
    x2: 1.2,
    y1: 0.9,
    y2: 1.5
}

// Function to check overlap
function doRectanglesOverlap(rectA, rectB):
    // Check if rectA is completely left of rectB
    if rectA.x2 <= rectB.x1:
        return false
    // Check if rectA is completely right of rectB
    if rectA.x1 >= rectB.x2:
        return false
    // Check if rectA is completely below rectB
    if rectA.y2 <= rectB.y1:
        return false
    // Check if rectA is completely above rectB
    if rectA.y1 >= rectB.y2:
        return false
    // If none of the above, rectangles overlap
    return true

// Test the function
result = doRectanglesOverlap(rect1, rect2)
print(result)  // Output will be true, since the rectangles overlap

验证你的例子

For your specific rectangles:

  • rect1's right edge (1.0) is greater than rect2's left edge (0.7) → not left of rect2
  • rect1's left edge (0.0) is less than rect2's right edge (1.2) → not right of rect2
  • rect1's top edge (1.0) is greater than rect2's bottom edge (0.9) → not below rect2
  • rect1's bottom edge (0.0) is less than rect2's top edge (1.5) → not above rect2

All non-overlap conditions fail, so the function returns true—which is correct, since the overlapping area is [0.7, 1.0] × [0.9, 1.0].

内容的提问来源于stack exchange,提问作者shahmeer arhsad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:54:10