動態規劃-最大的正方形面積

題目表述

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.

思路

使用動態規劃來求解,算法時間複雜度O(n^2)。

dp[i][j] : 以(i, j)爲右下角的面積最大的正方形的邊長。

初始條件:最上面一行,最左邊一列,可以直接得到dp值。

更新公式:matrix[i][j] == ‘0’ - > dp[i][j] = 0

matrix[i][j] == ‘1’ - > dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - 1], dp[i][j - 1]) + 1

代碼

#include<iostream>
#include<vector>
const int _MAX = 10;

using namespace std;

char matrix[_MAX][_MAX];
int dp[_MAX][_MAX];

int min3(int a, int b, int c){
    a = a < b ? a : b;
    return a < c ? a : c;
}

int main(){
    int n, m;
    cin>>n>>m;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            cin>>matrix[i][j];
        }
    }

    
    int res = 0;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            if(matrix[i][j] == 1)dp[i][j] = 1;
            else dp[i][j] = 0;
        }
    }

    for(int i = 1; i < n; i++){
        for(int j = 1; j < m; j++){
            if(matrix[i][j] == '1'){
                dp[i][j] = min3(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1;
                res = res > dp[i][j] ? res : dp[i][j];
            }
        }
    }
    cout<<res * res<<endl;
    return 0;
}

/* 
4 5
1 0 1 0 0 
1 0 1 1 1 
1 1 1 1 1 
1 0 0 1 0 
 */

更多內容訪問 omegaxyz.com
網站所有代碼採用Apache 2.0授權
網站文章採用知識共享許可協議BY-NC-SA4.0授權
© 2020 • OmegaXYZ-版權所有 轉載請註明出處

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章