算法代码

最大正方形

2020-09-07  本文已影响0人  windUtterance

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

示例
输入:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
输出: 4

作者:lzhlyle
链接:https://leetcode-cn.com/problems/maximal-square/solution/li-jie-san-zhe-qu-zui-xiao-1-by-lzhlyle/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Java代码

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];

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

猜你喜欢

热点阅读