Leetcode: 最大正方形(Maximal Square)(C++)

17 篇文章 0 订阅
17 篇文章 0 订阅

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

Example:

Input: 

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Output: 4

给定一个填充有0和1的二维二进制矩阵,找到仅包含1的最大正方形并返回其面积。


这题完全不知道出题者想考什么,我就随便写了点。如果有大佬知道的话,欢迎留言

我这边大概就是遍历每个点,如果明显不符合的直接跳过。符合的就检查它右下一圈,然后循环直到它右下一圈中有0 。最后得出的就是结果了。

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        // check and get size
        int x_size = matrix.size(), result_len = 0, len, buffer;
        if(!x_size)
            return 0;
        int y_size = matrix.at(0).size();
        if(!y_size)
            return 0;
        for (int x = 0; x < x_size - result_len; x++) {
		    for (int y = 0; y < y_size - result_len; y++) {
                // if element is 1 and remaining length > result length
			    if (matrix.at(x).at(y) == '1' && min(x_size - x, y_size - y) > result_len) {
                    // calculate the length of max square (left top is x,y)
				    for (len = 1; len < min(x_size - x, y_size - y); len++) {
					    buffer = 1;
					    for (int i = x; i < len + x; i++)
						    buffer &= matrix.at(i).at(y + len) - '0';
					    for (int i = y; i < len + y; i++)
						    buffer &= matrix.at(x + len).at(i) - '0';
					    buffer &= matrix.at(x + len).at(y + len) - '0';
					    if (buffer == 0) // not square
					    	break;
				    }
				    if (len > result_len)
				    	result_len = len;
			    }
		    }
	    }
        return result_len * result_len;
    }
};

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值