首页 > 代码库 > [LeetCode] Maximal Square

[LeetCode] Maximal Square

Maximal Square

Given a 2D binary matrix filled with 0‘s and 1‘s, find the largest square containing all 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.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

解题思路:

最值问题考虑动态规划算法。设d[i][j]表示以matrix[i][j]为右下角的最慷慨阵大小,则有:

d[i][j] = 0; matrix[i][j]=‘0‘时

d[i][j] = 1; matrix[i][j]=‘1‘且(i==0||j==0)时

d[i][j] = pow(min(min(sqrt(d[i-1][j-1]), sqrt(d[i-1][j])), sqrt(d[i][j-1])) + 1, 2); 其它情况。

然后用一个变量maxSquare记录全局最大的方阵就可以。

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        int n = matrix.size();
        if(n==0){
            return 0;
        }
        int m = matrix[0].size();
        vector<vector<int>> d(n, vector<int>(m, 0));    //以matrix[i][j]为右下角的最慷慨阵大小
        int maxSquare=0;
        
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(matrix[i][j]==‘0‘){
                    d[i][j] = 0;
                }else{
                    if(i>0&&j>0){
                        d[i][j] = (int)pow(min((int)min((int)sqrt(d[i-1][j-1]), (int)sqrt(d[i-1][j])), (int)sqrt(d[i][j-1])) + 1, 2);
                    }else{
                        d[i][j] = 1;
                    }
                    maxSquare = max(maxSquare, d[i][j]);
                }
            }
        }
        
        return maxSquare;
    }
};

[LeetCode] Maximal Square