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

如何用JavaScript判断二维布尔数组选中项是否构成矩形或正方形

判断二维布尔数组是否构成矩形/正方形的简洁实现

核心逻辑

  1. 提取所有值为true的坐标点
  2. 通过这些点的最大/最小行、列确定候选矩形范围
  3. 验证两个关键条件:
    • 实际标记点数量等于矩形范围的总点数(避免缺漏)
    • 矩形范围内的所有点都为true(避免额外点或不完整)

TypeScript 实现代码

function isRectangleOrSquare(proposedArray: boolean[][]): boolean {
    // 收集所有true的坐标 [行索引, 列索引]
    const truePoints: [number, number][] = [];
    proposedArray.forEach((row, rowIdx) => {
        row.forEach((val, colIdx) => {
            if (val) truePoints.push([rowIdx, colIdx]);
        });
    });

    const pointCount = truePoints.length;
    // 边界情况处理
    if (pointCount === 0) return false;
    if (pointCount === 1) return true; // 1x1 视为正方形,不需要可删除此行
    if (pointCount < 4) return false;

    // 获取矩形的边界值
    const rows = truePoints.map(p => p[0]);
    const cols = truePoints.map(p => p[1]);
    const minRow = Math.min(...rows);
    const maxRow = Math.max(...rows);
    const minCol = Math.min(...cols);
    const maxCol = Math.max(...cols);

    // 计算矩形区域的理论总点数
    const expectedTotal = (maxRow - minRow + 1) * (maxCol - minCol + 1);
    if (expectedTotal !== pointCount) return false;

    // 验证矩形范围内所有点都是true(确保没有缺漏)
    for (let r = minRow; r <= maxRow; r++) {
        for (let c = minCol; c <= maxCol; c++) {
            if (!proposedArray[r][c]) return false;
        }
    }

    return true;
}

关键说明

  • 单点场景:如果业务不认可1x1为正方形,直接删除if (pointCount === 1) return true;即可
  • 性能优化:数组规模极大时,可在收集坐标的同时计算极值,避免二次遍历坐标数组
  • 无效场景覆盖:自动排除点数量不足、缺角点、额外点等非矩形情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:50:22