如何找到最小的方块并在2D矩阵中计数

时间:2016-02-16 21:20:26

标签: java

该程序在数组中找到最大方块。

我如何找到最小的方块和它们的数量。

我怎样才能找到第一个最小方块的索引。

给定数组包含0,1布尔值。

public static void printMinSubSquare(int[][] M) {
    int i, j;
    int[][] S;
    S = new int[6][5];
    int max_of_s, max_i, max_j;
    /* Set first column of S[][]*/
    for (i = 0; i < 6; i++) {
        S[i][0] = M[i][0];
    }
    /* Set first row of S[][]*/
    for (j = 0; j < 5; j++) {
        S[0][j] = M[0][j];
    }
    /* Construct other entries of S[][]*/
    for (i = 1; i < 6; i++) {
        for (j = 1; j < 5; j++) {
            if (M[i][j] == 1) {
                S[i][j] = Math.min(Math.min(S[i][j - 1], S[i - 1][j]), S[i - 1][j - 1]) + 1;
                System.out.println(S[i][j]);
            } else {
                S[i][j] = 0;
            }
        }
    }
    /* Find the entry, and indexes of maximum entry 
     in S[][] */
    max_of_s = S[0][0];
    max_i = 0;
    max_j = 0;
    for (i = 0; i < 6; i++) {
        for (j = 0; j < 5; j++) {
            if (max_of_s < S[i][j]) {
                max_of_s = S[i][j];
                max_i = i;
                max_j = j;
            }
        }
    }
    System.out.println("\n Maximum size sub-matrix is: \n");
    for (i = max_i; i > max_i - max_of_s; i--) {
        for (j = max_j; j > max_j - max_of_s; j--) {
            System.out.print(M[i][j]);
        }
        System.out.print("\n");
    }
}
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    int[][] M = {{0, 1, 1, 0, 1},
    {1, 1, 0, 1, 0},
    {1, 1, 0, 0, 1},
    {1, 1, 1, 1, 1},
    {1, 0, 1, 1, 1},
    {0, 1, 1, 1, 1}};
    printMinSubSquare(M);
}

0 个答案:

没有答案