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

分析

要找到每一个位置的最大正方形,用result变量来存储整个矩阵中最大的正方形。

记录最大正方形的方式,用的是记录正方形的最大边长,这样面积就很容易能够知道。

用一个二维数组nums来记录当前正方形的最大边长,当在某个位置的时候,如果当前位置是0,那么它的nums记录值也就是0,如果当前位置是1,那么它的nums记录就应该是自己本身的边长 1 + min(上, 左, 左上) ,因为要根据上,左,左上这三个位置中最小的长度来定本身长度。

代码

class Solution {
    public int maximalSquare(char[][] matrix) {
        int result = 0;

        int row = matrix.length;
        if (row == 0) return 0;
        int col = matrix[0].length;
        int len = 0;

        int[][] nums = 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'){
                    nums[i][j] = Math.min(nums[i-1][j-1], Math.min(nums[i-1][j], nums[i][j-1])) + 1;
                }
                result = Math.max(result,nums[i][j]);
            }
        }

        return result*result;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38595487/article/details/83278391