leetcode 221. 最大正方形

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

 

示例 1:


输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:4
示例 2:


输入:matrix = [["0","1"],["1","0"]]
输出:1
示例 3:

输入:matrix = [["0"]]
输出:0
 

提示:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j] 为 '0' 或 '1'

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximal-square
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

采用动态规划,每个坐标点的长方形长度都和它的前面三个[(i, j - 1), (i - 1, j), (i - 1, j - 1)]有关系,取最小的 + 1即可。

    public int maximalSquare(char[][] matrix) {
        int x = matrix.length;
        int y = matrix[0].length;

        int[][] arr = new int[x + 1][ y + 1];
        int max = 0;
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                if (matrix[i][j] == '1') {
                    arr[i + 1][j + 1] = Math.min(arr[i][j + 1], Math.min(arr[i + 1][j],arr[i][j])) + 1;
                    max = Math.max(max, arr[i + 1][j + 1]);
                }
            }
        }
        return max * max;
    }

posted @ 2021-04-30 15:31  旺仔古李  阅读(39)  评论(0编辑  收藏  举报