动态规划-221-最大的正方形

Description:

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.


问题描述:

一个矩阵,其中元素为’0’或者’1’,找出最大的只包含‘1’的正方形,并且返回它的面积


问题分析

动态规划
状态dp[i][j], 表示以[i, j]作为正方形的右下角的坐标的最大的只包含‘1’的正方形的面积
转换为若matrix[i][j] == ‘1’,dp[i][j] = Math.min(dp[i][j - 1], Math.min(dp[i - 1][j - 1], dp[i - 1][j])) + 1

如果想详细了解如何得出这个递推式的话,可以看看这条链接:
https://leetcode.com/problems/maximal-square/discuss/61803/Easy-DP-solution-in-C++-with-detailed-explanations-(8ms-O(n2)-time-and-O(n)-space)


解法1(二维dp)

public class Solution {
    public int maximalSquare(char[][] matrix) {
        int rows = matrix.length, cols = rows > 0 ? matrix[0].length : 0;

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

        return maxsqlen * maxsqlen;
    }
}

解法2(一维dp):

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

        int[] dp = new int[matrix[0].length + 1];
        int max = 0;
        int tmp1 = 0;
        int tmp2 = 0;

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

        return max * max;
}
}

你可能感兴趣的:(算法与数据结构,leetcode全解)