簡體   English   中英

Java - 檢查矩形是否“適合”二維數組(二維裝箱)

[英]Java - Check if a rectangle "fits" into a 2 dimensional array (2d bin packing)

所以基本上我想創建一個方法,它將一個二維數組作為 1 個參數,一個矩形的寬度和高度作為其他 2 個參數。 二維數組僅包含二進制數(0 - 空單元格,1 - 取單元格)。 如果 bin 中仍有足夠的空間來容納矩形,則該方法應返回 true。

我的主要問題是我不知道如何遍歷二維數組,同時檢查數組中是否確實存在 rectHeight*rectWidth 大小的空白空間。

現在我只檢查 4 個頂點是否可用,但這顯然並不總是足夠的。

for (int j = y; j < y + rowHeight - rectHeight + 1; j++){
    for (int k = 0; k < bin[j].length - rectWidth + 1; k++){
        if (bin[j][k] == 0 && bin[j][k + rectWidth - 1] == 0 && bin[j + rectHeight - 1][k] == 0 && bin[j + rectHeight - 1][k + rectWidth - 1] == 0){
            isOne = true;
            for (int l = j; l < j + rectHeight; l++){
                for (int m = k; m < k + rectWidth; m++){
                    bin[l][m] = not_positioned.get(i).getId();
                }
            }
            not_positioned.remove(i);
        }
    }
}

在兩個循環中實現會更容易(每個循環在一個單獨的方法中):

//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;
    }

您可能想要添加一些有效性檢查(如正寬度和高度)。

您可以使用覆蓋圖,其中空單元格是頂點:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM