joshita / dev

Published

- 1 min read

Maximum square problem

img of Maximum square problem

Maximal square

Given an m x n binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area. Input: matrix = [[“1”,“0”,“1”,“0”,“0”],[“1”,“0”,“1”,“1”,“1”],[“1”,“1”,“1”,“1”,“1”],[“1”,“0”,“0”,“1”,“0”]] Output: 4

TotalValue

       private int maximalSquare(int [][] matrix) {
        int maxLen=0;
        int row = matrix.length;
        int col = matrix[0].length;
        int[][] dp = new int[row + 1][col + 1];

        for (int i=1; i < row; i ++) {
            for (int j=1; j < col; j++) {
                if(matrix[i-1][j-1]==1){
                    dp[i][j] = Math.min(Math.min(matrix[i][j-1], matrix[i-1][j]), matrix[i-1][j-1]) + 1;
                    maxLen = Math.max(maxLen, dp[i][j]);
                }
            }
        }
        return maxLen*maxLen;
    }