在图像中寻找矩形

问题描述

想象一下我们有一个图像。我们将此图像表示为一个简单的二维数组,其中每个像素都是 1 或 0。

已知您获得的图像在 1 的背景上可能有许多不同的 0 矩形。编写一个函数,接收图像并返回所有 0 个矩形的坐标——左上角和右下角;或左上角,宽度和高度。

image1 = [
[0,1,1],[1,[0,0],]

样本输出变化(只需要一个):

findRectangles(image1) =>
// (using top-left-row-column and bottom-right):
[
[[0,0]],[[2,[2,3],[3,5]],[[3,[5,1]],[[5,[6,4]],[[7,6],[7,6]],]
// (using top-left-x-y and width/height):
[
[[0,[[0,2],2]],[[1,3]],5],[[6,7],]

其他测试用例:

image2 = [
[0],]

findRectangles(image2) =>
// (using top-left-row-column and bottom-right):
[
[[0,]

// (using top-left-x-y and width/height):
[
[[0,]

image3 = [
[1],]

findRectangles(image3) => []

image4 = [
[1,]

findRectangles(image4) =>
// (using top-left-row-column and bottom-right or top-left-x-y and width/height):
[
[[1,]

n: number of rows in the input image
m: number of columns in the input image

以下是我为查找矩形而编写的代码,但不确定如何创建问题中所示的输出矩阵。

我的方法是从上到下逐行扫描。对于每一行,记住 2 个 1 的每个组合并将其推入一个哈希集。如果我们再次找到该组合,则表示它是一个矩形。

public static boolean isRectangle(int matrix[][]) {
    // finding row and column size
    int rows = matrix.length;
    if (rows == 0)
        return false;
    int columns = matrix[0].length;

    /*
     * y1=0 x1=1
     *      x2=2
     */
    HashMap<Integer,HashSet<Integer>> table = new HashMap<>();
    int output[][];

    for (int y1 = 0; y1 < rows; y1++) {
        for (int x1 = 0; x1 < columns - 1; x1++) {
            for (int x2 = x1 + 1; x2 < columns; x2++) {
                // if found two 1's in a column
                if (matrix[y1][x1] == 1 && matrix[y1][x2] == 1) {
                    // check if there exists 1's in same
                    // row prevIoUsly then return true
                    if (table.containsKey(x1) && table.get(x1).contains(x2)) {
                        return true;
                    }
                    if (table.containsKey(x2) && table.get(x2).contains(x1)) {
                        return true;
                    }

                    // store the indexes in hashset
                    if (!table.containsKey(x1)) {
                        HashSet<Integer> set = new HashSet<>();
                        set.add(x2);
                        table.put(x1,set);
                    } else {
                        table.get(x1).add(x2);
                    }
                    if (!table.containsKey(x2)) {
                        HashSet<Integer> set = new HashSet<>();
                        set.add(x1);
                        table.put(x2,set);
                    } else {
                        table.get(x2).add(x1);
                    }
                }
            }
        }
    }
    return false;
}

public static void main(String args[]) {
    int mat[][] = {
            {1,1},{1,0},{0,1}};

    if (isRectangle(mat))
        System.out.print("TRUE");
    else
        System.out.print("FALSE");
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)