动态规划——LeetCode221最大正方形

在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。

示例:

输入: 

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

输出: 4

题解关键思路:

这道题检查正方形的第四个角作递归
dp记录最大正方形的边长

 

代码:

class Solution {
    public int maximalSquare(char[][] matrix) {
        //只能总结经验吗??!!
        if ( matrix.length <= 0 || matrix[0].length <= 0 ) {
            return 0;
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int dp[][] = new int[row+1][col+1];

        int max = 0;
        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(dp[i-1][j] , dp[i][j-1])                      , dp[i-1][j-1] ) + 1;
                }
                max = Math.max( max , dp[i][j] );
            }
        }
        return max * max;
    }
}

 

posted @ 2019-11-19 23:43  great978  阅读(115)  评论(0编辑  收藏  举报