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

如何在二维int数组中找到四角匹配数组外四角的矩形?

解决方案:清晰拆解步骤实现矩形查找

我来帮你梳理下思路,其实你最初的方向是对的,只是没把逻辑拆解开导致混乱。我们可以把问题拆解成几个清晰的步骤来实现:

第一步:明确目标值

首先提取原二维数组的四个外四角值,这是我们要找的矩形的四个角必须匹配的目标:

int[][] arr = { {3, 4, 3, 5, -9}, {0, 4, 4, -8, 6}, {1, 1, 3, -9, 6}, {4, 3, -2, 5, 6}};
int topLeftVal = arr[0][0];       // 3
int topRightVal = arr[0][arr[0].length - 1]; // -9
int bottomLeftVal = arr[arr.length - 1][0]; // 4
int bottomRightVal = arr[arr.length - 1][arr[0].length - 1]; // 6

第二步:收集顶部行的有效列对

遍历每一行作为矩形的顶部行r1,在该行中找出所有满足「左列是topLeftVal,右列是topRightVal,且左列索引 < 右列索引」的列对(c1, c2)。这些列对是我们后续匹配底部行的关键:

List<int[]> validColumnPairs = new ArrayList<>();
int rowCount = arr.length;
int colCount = arr[0].length;

// 遍历所有可能的顶部行
for (int r1 = 0; r1 < rowCount; r1++) {
    // 收集当前行中所有等于topLeftVal的列索引
    List<Integer> leftCols = new ArrayList<>();
    // 收集当前行中所有等于topRightVal的列索引
    List<Integer> rightCols = new ArrayList<>();
    
    for (int c = 0; c < colCount; c++) {
        if (arr[r1][c] == topLeftVal) {
            leftCols.add(c);
        } else if (arr[r1][c] == topRightVal) {
            rightCols.add(c);
        }
    }
    
    // 生成所有有效的(c1, c2)列对(c1 < c2)
    for (int c1 : leftCols) {
        for (int c2 : rightCols) {
            if (c1 < c2) {
                validColumnPairs.add(new int[]{r1, c1, c2});
            }
        }
    }
}

这里我们把顶部行的索引r1也存在列对里,方便后续匹配底部行时定位。

第三步:匹配底部行,找到目标矩形

遍历所有可能的底部行r2(必须大于顶部行r1),检查该行是否存在某个已收集的列对(c1,c2),满足「c1列是bottomLeftVal,c2列是bottomRightVal」:

// 遍历所有可能的底部行
for (int r2 = 0; r2 < rowCount; r2++) {
    // 遍历所有有效的列对
    for (int[] pair : validColumnPairs) {
        int r1 = pair[0];
        int c1 = pair[1];
        int c2 = pair[2];
        
        // 确保底部行在顶部行下方,且列对匹配底部的两个目标值
        if (r2 > r1 && arr[r2][c1] == bottomLeftVal && arr[r2][c2] == bottomRightVal) {
            // 找到目标矩形,输出四个角的坐标
            System.out.println("找到目标矩形,四个角坐标:");
            System.out.printf("[%d,%d] (值:%d)、[%d,%d] (值:%d)%n", r1, c1, arr[r1][c1], r1, c2, arr[r1][c2]);
            System.out.printf("[%d,%d] (值:%d)、[%d,%d] (值:%d)%n", r2, c1, arr[r2][c1], r2, c2, arr[r2][c2]);
            // 如果只需要找第一个匹配的矩形,可以直接return结束程序
            return;
        }
    }
}

为什么这个思路更清晰?

你之前的思路是同时处理3/-9和4/6的情况,导致逻辑交织混乱。现在我们把问题拆成了「先找顶部行的有效列对」和「再用这些列对匹配底部行」两个独立环节,每个环节只关注单一目标,逻辑就清晰多了。

运行这段代码,会输出你示例中的目标矩形:

找到目标矩形,四个角坐标:
[0,2] (值:3)、[0,4] (值:-9)
[1,2] (值:4)、[1,4] (值:6)

内容的提问来源于stack exchange,提问作者achAmháin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:13:33