最大正方形问题一维dp数组解法

392 阅读1分钟

问题描述:

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

示例:

输入:

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

输出: 4

题目链接

思路:

以当前点为正方形右下角点出发,其成立的条件为当前点左边、上边、左上边的点都是“1”,符合“最小”思想,那么自然就可以构建dp方程:

if(matrix[row+1][col+1]=="1"):

dp[row+1][col+1] = min(dp[row][col+1],dp[row+1][col],dp[row][col]) + 1;

if(matrix[row+1][col+1] != "1"):

dp[row+1][col+1] = 0;

接下来可以对二维数组进行优化,构建一维滚动数组,难点在于对左上边点的判定,可以引入northwest(左上角标记),代码如下:

class Solution {
    public int maximalSquare(char[][] matrix) {
        if(matrix == null || matrix.length < 1 || matrix[0].length < 1){
            return 0;
        }
        int height = matrix.length;
        int width = matrix[0].length;
        int maxSide = 0;

        int[] dp = new int[width + 1];
        int northwest = 0;
        for(char[] chars : matrix){
            northwest = 0;
            for(int col = 0;col < width;col++){
                int nextNorthwest = dp[col+1];
                if(chars[col] == '1'){
                    dp[col+1] = Math.min(Math.min(dp[col+1],dp[col]),northwest) + 1;
                    maxSide = Math.max(dp[col+1],maxSide);
                }else {
                    dp[col+1] = 0;
                }
                northwest = nextNorthwest;
            }
        }
        return maxSide * maxSide;
    }
}

leetcode的官方题解解释的也很全面,建议看官方题解