leetcode 221. 最大正方形

leetcode 221. 最大正方形

题目详情

题目链接
在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。

  • 示例:
    输入:
    1 0 1 0 0
    1 0 1 1 1
    1 1 1 1 1
    1 0 0 1 0
    输出: 4

我的代码

class Solution {
public:
    vector<vector<char>> array;
    int rowLen, colLen;

    bool allOne(int row, int col, int res) {
        for (int i = 0; i <= res; ++i) {
            if (!((array[row + res][col + i] == '1') && (array[row + i][col + res] == '1'))) {
                return false;
            }
        }
        return true;
    }

    int getMaxSquare(int row, int col) {
        int res = 1;
        for ( ; (row + res < rowLen) && (col + res < colLen); ++res) {
            if (!allOne(row, col, res)) {
                return res;
            }
        }
        return res;
    }

    int maximalSquare(vector<vector<char>>& matrix) {
        array = matrix, rowLen = matrix.size();
        if (rowLen == 0) {
            return 0;
        }
        colLen = matrix[0].size();
        int res = 0;
        for (int row = 0; row < rowLen - res; ++row) {
            for (int col = 0; col < colLen - res; ++col) {
                if (matrix[row][col] == '1') {
                    res = max(res, getMaxSquare(row, col));
                }
            }
        }
        return res * res;
    }
};

我的成绩

执行结果:通过
执行用时 : 24 ms, 在所有 C++ 提交中击败了41.10%的用户
内存消耗 : 8.8 MB, 在所有 C++ 提交中击败了100.00%的用户

一些想法

本道题我的想法是遍历矩阵,如果遇到为‘1’的元素,就进行处理,获取当把该元素作为正方形左上顶点时的最大边长,需要注意的是对边界值的处理。

执行用时为 4 ms 的范例

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

思考

没看懂范例,是用的动态规划吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值