Maximal Square

本文介绍了一种寻找二维二进制矩阵中只包含1的最大正方形的方法,并提供了两种高效的实现方式:一种使用二维动态规划,另一种则通过一维数组优化空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

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

Code

Always remember to get rid of invalid input and deal with corner cases in the first place. We have the following state equations:

P[0][j] = matrix[0][j] (topmost row);
P[i][0] = matrix[i][0] (leftmost column);
For i > 0 and j > 0: 
    if matrix[i][j] = 0, P[i][j] = 0; 
    if matrix[i][j] = 1, P[i][j] = min(P[i - 1][j], P[i][j - 1], P[i - 1][j - 1]) + 1.

Thus, we have the following straightforward code:

int maximalSquare(vector<vector<char>>& matrix) {
    int m = matrix.size();
    if (!m) return 0;
    int n = matrix[0].size();
    vector<vector<int> > size(m, vector<int>(n, 0));
    int maxsize = 0;
    for (int j = 0; j < n; j++) {
        size[0][j] = matrix[0][j] - '0';
        maxsize = max(maxsize, size[0][j]);
    }
    for (int i = 1; i < m; i++) {
        size[i][0] = matrix[i][0] - '0';
        maxsize = max(maxsize, size[i][0]);
    }
    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++) {
            if (matrix[i][j] == '1') {
                size[i][j] = min(size[i - 1][j - 1], min(size[i - 1][j], size[i][j - 1])) + 1;
                maxsize = max(maxsize, size[i][j]);
            }
        }
    }
    return maxsize * maxsize;
}

Actually, space can be saved by using a one-dimension array

```
class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        //Get rid of invalid input
        int row = matrix.size();
        if(!row)
            return 0;
        int col = row > 0 ? matrix[0].size() : 0;

        vector<int> dp(row+1,0);
        int maxsize = 0, pre = 0;
        for(int j = 0; j < col; j++)
            for(int i = 1; i <= row; i++){
                int tmp = dp[i];
                if(matrix[i - 1][j] == '1'){
                    dp[i] = min(dp[i], min(dp[i - 1], pre)) + 1;
                    maxsize = max(maxsize, dp[i]);
                }
                else
                    dp[i] = 0;
                pre = tmp;
            }
        return maxsize * maxsize;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值