leetcode 221. 最大正方形 medium
题目描述:
在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。
示例:
输入:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
输出: 4
解题思路:
方法一:
第一反应就是用求最大矩形的方法做,也就是按行来求直方图的最大面积
方法二:
dp。
dp(i, j)=min(dp(i−1, j), dp(i−1, j−1), dp(i, j−1))+1 (if vec【i】【j】=1)
dp(i,j)=0 (if vec【i】【j】=0)
dp【i】【j】 表示的含义是必须以i,j为右下角的 最大正方形的边长
代码:
// 单调栈
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if(matrix.empty() || matrix[0].empty())
return 0;
int res=0;
// 按行来,用单调栈计算直方图的最大面积
vector<int> vec(matrix[0].size(),0);
for(int i=0;i<matrix.size();++i){
for(int j=0;j<vec.size();++j){
vec[j]= matrix[i][j]=='1'?vec[j]+1:0;
}
res = max(res,core(vec));
}
return res;
}
int core(const vector<int> & vec){
int res=0;
stack<int> stk;
for(int i=0;i<vec.size();++i){
while(stk.size() && vec[i]<=vec[stk.top()]){
int index=stk.top();
stk.pop();
int end=i;
int start=stk.empty()?-1:stk.top();
int area= (end-start-1)>=vec[index]?vec[index]*vec[index]:0;
res= max(res,area);
}
stk.push(i);
}
int end=vec.size();
while(stk.size()){
int index=stk.top();
stk.pop();
int start=stk.empty()?-1:stk.top();
int area= (end-start-1)>=vec[index]?vec[index]*vec[index]:0;
res= max(res,area);
}
return res;
}
};
//dp
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if(matrix.empty() || matrix[0].empty())
return 0;
int res=0;
vector<vector<int>> dp(matrix.size(),vector<int>(matrix[0].size(),0));
for (int i = 0; i < matrix.size(); ++i) {
for (int j = 0; j < matrix[0].size(); ++j) {
if (i == 0 || j == 0) dp[i][j] = matrix[i][j] - '0';
else if (matrix[i][j] == '1') {
dp[i][j] = min(dp[i - 1][j - 1], min(dp[i][j - 1], dp[i - 1][j])) + 1;
}
res = max(res, dp[i][j]);
}
}
return res * res;
}
};