算法: 最大正方形面积221. Maximal Square

Posted AI架构师易筋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法: 最大正方形面积221. Maximal Square相关的知识,希望对你有一定的参考价值。

221. Maximal Square

Given an m x n binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.

Example 1:

Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 4

Example 2:

Input: matrix = [["0","1"],["1","0"]]
Output: 1

Example 3:

Input: matrix = [["0"]]
Output: 0

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 300
  • matrix[i][j] is '0' or '1'.

动态规划解法

dp[i][j] 代表位置 (i, j) 处最大正方形 ENDING 的边长
dp[i][j]表示右下角位于 的正方形的长度(i, j)
如果此单元格的值也是1,则正方形的长度是以下各项中的最小值:上方、其左侧和对角线左上角值 +1。因为如果一侧短或缺失,则不会形成正方形。

class Solution 
    public int maximalSquare(char[][] matrix) 
        int rows = matrix.length;
        int cols = matrix[0].length;
        int maxEdge = 0;
        int[][] dp = new int[rows + 1][cols + 1];
        for (int r = 0; r < rows; r++) 
            for (int c = 0; c < cols; c++) 
                if (matrix[r][c] == '1') 
                    dp[r + 1][c + 1] = Math.min(dp[r][c], Math.min(dp[r + 1][c], dp[r][c + 1])) + 1;
                    maxEdge = Math.max(maxEdge, dp[r + 1][c + 1]);
                
            
        
        return maxEdge * maxEdge;
    

参考

https://leetcode.com/problems/maximal-square/discuss/61802/Extremely-Simple-Java-Solution-%3A)

以上是关于算法: 最大正方形面积221. Maximal Square的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 221. Maximal Square 最大正方形(中等)

[Leetcode221]最大面积 Maximal Square

[LeetCode] 221. Maximal Square 最大正方形

题目地址(221. 最大正方形)

221最大正方形

leetcode 221. 最大正方形(dp)