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;
}
};
思考
没看懂范例,是用的动态规划吗?