Largest Square Surrounded By One

public class Solution { public int largestSquareSurroundedByOne(int[][] matrix) { int rows = matrix.length; int columns = matrix[0].length;

    int[][] left = new int[rows][columns];
    int[][] up = new int[rows][columns];


    int globalMax = 0;

    populate(left, up, matrix);

    for (int i = 1; i < rows; i++){
        for (int j = 1; j < columns; j++){
            if (matrix[i][j] == 1){
                int curMax = check(i, j, left, up);
                globalMax = Math.max(globalMax, curMax);
                //12 7

            }
        }
    }

    return globalMax;


}

private void populate(int[][] left, int[][] up, int[][] matrix){

    int rows = matrix.length;
    int columns = matrix[0].length;

    //populate left wall
    for (int i = 0; i < rows; i++){
        left[i][0] = matrix[i][0] == 1 ? 1 : 0;
    }

    //populate ceiling
    for (int i = 0; i < columns; i++){
        up[0][i] = matrix[0][i] == 1 ? 1 : 0;
    }

    //populate left
    for (int i = 0; i < rows; i++){
        for(int j = 1; j < columns; j++){
            if (matrix[i][j] == 1){
                //inherit from left tile
                left[i][j] = left[i][j - 1] + 1;
            }
        }
    }

    //populate up
    for(int i = 1; i < rows; i++){
        for(int j = 0; j < columns; j++){
            if (matrix[i][j] == 1){
                //inherit from above
                up[i][j] = up[i - 1][j] + 1;
            }
        }
    }
}

//assuming current slot is a '1'
private int check(int x, int y, int[][]left, int[][]up){
    //take min between left and up, thats the max square size
    //iterate through each to check if filled

    int maxSize = Math.min(left[x][y], up[x][y]);
    for (int i = maxSize - 1; i > 0; i--){ //- 1 to account for 1x1 tile on itself
        //ceiling of i size square
        int ceilingSize = left[x - i][y];

        //leftwall of i size square
        int leftSize = up[x][y - i];

        if (ceilingSize >= maxSize && leftSize >= maxSize){
            return i + 1;
        }
    //1 
    }

    return 1;
}

}

Mistakes made:

  1. When checking, Math.min determines the largest box that can be created

  2. top and ceiling base cases must be separately populated to account for cases where N != M

Last updated

Was this helpful?