[LeetCode]221. Maximal Square

[LeetCode]221. Maximal Square

题目描述

这里写图片描述

思路

一种思路是直方图做法,可以解扩展到矩形的情况,见另一篇博客
[LeetCode]85. Maximal Rectangle

另外的思路是动态规划解法

给出的样例输入为

matrix01234
010100
110111
211111
310010

对应的状态矩阵

dp01234
010100
110111
211122
310010

代码

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int maximalSquare(vector<string>& matrix) {
        if (matrix.size() == 0)
            return 0;
        int row = matrix.size(),
            col = matrix[0].size(),
            res = 0;
        vector<vector<int>> dp(row, vector<int>(col));
        for(int i = 0; i < row; ++i)
            for (int j = 0; j < col; ++j) {
                if (i == 0 || j == 0)
                    dp[i][j] = (matrix[i][j] == '1');
                else if (matrix[i][j] == '0')
                    dp[i][j] = 0;
                else {
                    int k = 1;
                    for (; k <= dp[i - 1][j - 1]; ++k)
                        if (dp[i - k][j] == 0 || dp[i][j - k] == 0)
                            break;
                    dp[i][j] = k;
                }
                res = max(res, dp[i][j]);
            }
        return res * res;
    }
};

int main() {
    vector<string> matrix = { "0010","1111","1111","1110","1100","1111","1110" };
    Solution s;
    cout << s.maximalSquare(matrix) << endl;

    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值