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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,921評論 0 33
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,100評論 0 23
  • 早上進(jìn)教室,馬浩軒安排值日生值日,并督促他們打掃單位。憨憨的他,有耐心,有責(zé)任心;羅一收作業(yè)本,他活躍,讓...
    呵媽閱讀 213評論 0 1
  • 我愛秋天 秋天到了.濃郁的桂花迷人最,.醉人香啊我喜歡. 秋天真好?。簼M山的楓葉紅了。 秋天你真好.你知道什么時候...
    花丹俏閱讀 307評論 0 0
  • 最近在讀《拖延心理學(xué)》,恰好就看到了Tim Urban的那次TED演講,你有拖延癥么? 覺得講的相當(dāng)好,不論是從演...
    洛嘉_yang閱讀 858評論 8 5

友情鏈接更多精彩內(nèi)容