Java - 检查矩形是否“适合”二维数组(2d bin包装)

时间:2017-10-04 11:31:51

标签: java arrays multidimensional-array bin-packing

所以基本上我想创建一个方法,将2d数组作为1参数,将矩形的宽度和高度作为其他2个参数。 2d数组仅包含二进制数(0 - 空单元,1 - 采用单元)。如果bin中仍有足够的位置来保存矩形,则该方法应返回true。

我的主要问题是我不知道如何迭代2d数组,同时检查数组中是否存在rectHeight * rectWidth大小的空格。

现在我只是检查4个顶点是否可用,但这显然不够。

var v = new Vehicle();

2 个答案:

答案 0 :(得分:1)

在两个循环中实现它们会更容易(每个循环都在一个单独的方法中):

//test data 
private static int[][] bin = {
            {1,1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1,1},
            {1,1,1,1,0,0,0,1,1,1},
            {1,1,1,1,0,0,0,1,1,1},
            {1,1,1,1,0,0,0,1,1,1},
            {1,1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1,1},
          };

public static void main(String[] args) {

        System.out.println(isEnoughtSpace(1, 1));// output - true
        System.out.println(isEnoughtSpace(2, 2));// output - true
        System.out.println(isEnoughtSpace(3, 3));// output - true
        System.out.println(isEnoughtSpace(1, 3));// output - true
        System.out.println(isEnoughtSpace(3, 1));// output - true
        System.out.println(isEnoughtSpace(4, 1));// output - false
        System.out.println(isEnoughtSpace(4, 5));// output - false
        System.out.println(isEnoughtSpace(11,11));// output - false
        System.out.println(isEnoughtSpace(0,0));// output - true
    }

    private static boolean isEnoughtSpace(int rectHeight, int recWidth) {

        for(int row = 0; row <= (bin.length - rectHeight); row++) {

            for(int col = 0; col <= (bin[0].length - recWidth); col++) {

                if(isEnoughtSpace(row, col, rectHeight, recWidth)) {
                    return true;
                }
            }
        }
        return false;
    }

    private static boolean isEnoughtSpace(int rowIndex, int colIndex,int rectHeight, int recWidth) {

        for(int row = rowIndex; row < (rowIndex+rectHeight) ; row ++) {

            for(int col = colIndex; col < (colIndex+recWidth) ; col++) {
                if(bin[row][col] == 1 ) {
                    return false;
                }
            }
        }
        return true;
    }

您可能需要添加一些有效性检查(例如正宽度和高度)。

答案 1 :(得分:0)

您可以使用覆盖图,其中空单元格是顶点:

https://en.wikipedia.org/wiki/Covering_graph

相关问题