加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

leetcode221 - Maximal Square - medium

发布时间:2020-12-14 04:19:38 所属栏目:大数据 来源:网络整理
导读:Given a 2D binary matrix filled with 0‘s and 1‘s,find the largest square containing only 1‘s and return its area. Example: Input: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 Output: 4 ? ? DP。 思路: 知道从当前格子向左上角延伸出最大的正方形

Given a 2D binary matrix filled with 0‘s and 1‘s,find the largest square containing only 1‘s and return its area.
Example:
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
?
?
DP。
思路:
知道从当前格子向左上角延伸出最大的正方形边长有信息帮助。
等我们遍历到矩阵中某个1的时候,想要让这个1做出拼正方形的贡献,有三种途径:
- 帮助左边的最大正方形,那要求现在这列往上也有足够的1;
- 帮助上面的最大正方形,那要求这行往左也有足够的1;
- 帮助左上的最大正方形,那要求现在这列往上这行往左都有足够的正方形。
这个"足够"有一种三者互相制约的感觉,最后利用这种制约关系把这三者合并到一起处理的方法就是:选出三者里最小的数,+1,就是我当前能拼出最大正方形的边长。因为取了最小值,那对三个维度都“足够”了。
?
定义:dp[i][j]说明对原始matrix,从(I,j)开始向左上角尽量延伸,能拼出的最大正方形的边长。注意(i,j)点必须被包括。
状态转移方程:dp[i][j] = min(dp[i - 1][j - 1],dp[i - 1][j],dp[i][j - 1]) + 1。对所有当前值为1的点。
扫描方向:从上到下,从左到右。依赖左上左上,常规。
?
细节:
1.最后返回值是面积,和你dp过程中求的边长定义不同,简单乘一乘后才能返回。
?
实现:
class Solution {
    public int maximalSquare(char[][] matrix) {
        // input check.
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }
        
        int edge = 0;
        // dp[i][j]: find the max rectangle for area of [?:i][?:j],and save the edge length of it. 
        int[][] dp = new int[matrix.length + 1][matrix[0].length + 1];
        for (int i = 1; i < dp.length; i++) {
            for (int j = 1; j < dp[0].length; j++) {
                if (matrix[i - 1][j - 1] == ‘1‘) {
                    dp[i][j] = Math.min(dp[i - 1][j - 1],Math.min(dp[i  - 1][j],dp[i][j - 1])) + 1;
                    edge = Math.max(edge,dp[i][j]);
                }
            }
        }
        // P1: 最后返回的是面积,而不是dp过程求出来的边长!要做转换。
        return edge * edge;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读