在多维数组中查找坐标

时间:2019-01-30 15:39:10

标签: java multidimensional-array

我有一个int[][]数组,如下所示:

int[][] arr = { {3, 4, 3, 5, -9}, 
                {0, 4, 4, -8, 6}, 
                {1, 1, 3, -9, 6}, 
                {4, 3, -2, 5, 6}};

实际的问题是在2维数组中找到一个矩形,该矩形的每个角与2维数组中的角元素具有相同的值。例如,角分别是3,-9、4和6。结果矩形是[0,2],[0,4],[1、2],[1,4]处的矩形。

我的尝试是首先找出每行上所有[3,-9]的位置,例如,第一行在[{0,0},{0,4}处有两个]和[{0,2},{0,4}]。

我可以做标准嵌套for循环到找到每个3,并且每个9:

for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr[i].length; j++) {
    // if value is 3, store the co-ordinates
    // if value is 9, store the co-ordinates (separately)
    }
}

但是随后我被迫遍历2个列表(分别是3s和-9s),并检查每3个列表是否在同一行中有一个-9,并且在该行之后是-9,如果是这样,将两个坐标合并并存储在一起。

然后当然我已经做的4S和6S相同,它已迅速成为一个大的烂摊子。

也许我看错了一切,可以将其视为XY Problem

我的问题:如何在2d数组中找到一个矩形,且该矩形的角与2d数组的外角相匹配?

1 个答案:

答案 0 :(得分:1)

普通搜索怎么样?

public static List<Point> findRectangle(int[][] arr) {
    int height = arr.length;
    int width = arr[0].length;

    for (int rowTop = 0; rowTop < height - 1; rowTop++) {
        for (int colLeft = rowTop == 0 ? 1 : 0; colLeft < width - 1; colLeft++) {
            // find new left-top corner
            if (arr[rowTop][colLeft] != arr[0][0])
                continue;

            int colRight = colLeft + 1;

            while (colRight < width && arr[rowTop][colRight] != arr[0][width - 1]) {
                colRight++;
            }

            if (colRight == width)
                continue;

            // find new left-bottom corner
            int rowBottom = rowTop + 1;

            while (rowBottom < height && arr[rowBottom][colLeft] != arr[height - 1][0]) {
                rowBottom++;
            }

            if (rowBottom == height || arr[rowBottom][colRight] != arr[height - 1][width - 1])
                continue;

            return Arrays.asList(
                    new Point(rowTop, colLeft),
                    new Point(rowTop, colRight),
                    new Point(rowBottom, colLeft),
                    new Point(rowBottom, colRight));
        }
    }

    return Collections.emptyList();
}

public static final class Point {

    private final int row;
    private final int col;

    public Point(int row, int col) {
        this.row = row;
        this.col = col;
    }
}
相关问题