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;
}
};