221. Maximal Square

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 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.

DP, if matrix[i][j] belongs to a square and it is the bottom-right element, in this case, the left, top, and top-left neighbours of this are all required to bottom-right element of another square.

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

        int edge = 0;
        for(int i =0 ;i < matrix.length; i++){
            dp[i][0] = matrix[i][0] == '0' ? 0 : 1;
            edge = Math.max(dp[i][0], edge);
        }
        for(int i=0; i< matrix[0].length; i++){
            dp[0][i] = matrix[0][i] == '0' ? 0 : 1;
            edge = Math.max(dp[0][i], edge);
        }

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

            }
        }

        return edge * edge;
    }
}

results matching ""

    No results matching ""