Maximal Square

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

For example, given the following matrix:

1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0

Return 4.

Credits:Special thanks to @Freezen for adding this problem and creating all test cases.

Solution

public class Solution {
    public int maximalSquare(char[][] matrix) {
        if (matrix == null) return 0;
        int row = matrix.length;
        if (row == 0) return 0;

        int column = matrix[0].length;
        if (column == 0) return 0;

        int[][] dp = new int[row][column];
        for (int i = 0; i < column; i++) {
            if (matrix[0][i] == '1') {
                dp[0][i] = 1;
            }
        }

        for (int i = 0; i < row; i++) {
            if (matrix[i][0] == '1') {
                dp[i][0] = 1;
            }
        }

        for (int i = 1; i < row; i++) {
            for (int j = 1; j < column; j++) {
                if (matrix[i][j] == '1') {
                    dp[i][j] = Math.min(Math.min(dp[i - 1][j - 1], dp[i][j - 1]), dp[i - 1][j]) + 1;
                }
            }
        }

        int result = dp[0][0];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                result = Math.max(result, dp[i][j]);
            }
        }

        return result * result;
    }
}

results matching ""

    No results matching ""