LeetCode - Maximal Square / two-dimensional matrix largest square area

Q: Given a two-dimensional matrix of binary 0 and 1, to find the maximum square contains only 1 and returns its area.
Example:

Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Output: 4

A: quote: https://blog.csdn.net/fly_fly_zhang/article/details/90637370
we initialize a two-dimensional matrix dp, dp [i] [j ] expressed in its bottom right corner of the largest side length of the square. Traversing the original matrix, each found a 1, it will seek to bottom right corner of the largest side length of the square.
A square is determined from small to large process:
look at whether a node 1;
look 2/ 2 satisfies the range conditions.
Sequentially until n-/
n-range condition is satisfied.
Thus, this is a result of the establishment is established based on previous results, so use dp processing.
dp [i] [j] as well as top left corner is the subject of the second quadrant of its origin, in fact, is already known. So we set it to the lower right corner of the square, it is just the application of the conditions already.
While the other three vertices positions of the square actually obtained at long sides and in accordance with its neighbor it has been estimated. Which exists following formula:
\ [the DP [I] [J] = min (the DP [I-. 1] [J-. 1], the DP [I-. 1] [J], the DP [I, J-. 1]) +. 1 \]
the DP [. 1-I] [J-. 1] upper-left corner position
DP [i-1] [j ] to determine the position of the lower left corner
DP [i, j-1] to determine the position of the upper right corner.
The minimum length of the three sides of the square corresponding position can be determined.

    public int maximalSquare(char[][] matrix) {
        if(matrix==null||matrix.length==0||matrix[0]==null||matrix[0].length==0)
            return 0;
        int row=matrix.length;
        int col=matrix[0].length;
        int max=0;
        //因为矩阵最上面的点是以它自己为一个矩阵的,但是为了计算方便
        //我们假设它有
        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(dp[i-1][j],Math.min(dp[i-1][j-1],dp[i][j-1]))+1;
                   max=Math.max(dp[i][j],max); 
                }
            }
        }
        return max*max;
    }

Guess you like

Origin www.cnblogs.com/xym4869/p/12542525.html