221. Maximal Square

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

For example, given the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Return 4.

一刷
题解:由于是问能框住1的最大矩形的面积,于是我们用dynamic programming
如果a[i][j]==‘1’, 那么dp[i][j] = Math.min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1

public class Solution {
    public int maximalSquare(char[][] a) {
        if(a.length == 0) return 0;
        int m = a.length, n = a[0].length, result = 0;
        int[][] b = new int[m+1][n+1];
        int max = 0;
        for(int i=1; i<=m; i++){
            for(int j=1; j<=n; j++){
                if(a[i-1][j-1] == '1'){
                    b[i][j] = Math.min(Math.min(b[i][j-1], b[i-1][j-1]), b[i-1][j])+1;
                    max = Math.max(max, b[i][j]);
                }
            }
        }
        return max*max;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,973评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,547评论 0 23
  • 早上进教室,马浩轩安排值日生值日,并督促他们打扫单位。憨憨的他,有耐心,有责任心;罗一收作业本,他活跃,让...
    呵妈阅读 213评论 0 1
  • 我爱秋天 秋天到了.浓郁的桂花迷人最,.醉人香啊我喜欢. 秋天真好啊:满山的枫叶红了。 秋天你真好.你知道什么时候...
    花丹俏阅读 330评论 0 0
  • 最近在读《拖延心理学》,恰好就看到了Tim Urban的那次TED演讲,你有拖延症么? 觉得讲的相当好,不论是从演...
    洛嘉_yang阅读 863评论 8 5

友情链接更多精彩内容