版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011391629/article/details/86509227
Question
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
Algorithm
参照Solution
dp(i,j)=min(dp(i−1,j),dp(i−1,j−1),dp(i,j−1))+1.
Code
这里dp数组比matrix大,是因为方便代码处理,不然需要对matrix[0][0],matrix[1][0],matrix[0][1]做特殊处理。
class Solution {
public:
int min(int a, int b, int c){
if(a<b){
return a<c?a:c;
}
return b<c?b:c;
}
int maximalSquare(vector<vector<char>>& matrix) {
if(matrix.empty())
return 0;
int row = matrix.size();
int col = matrix[0].size();
vector<vector<int> > dp(row+1, vector<int>(col+1, 0));
int maxLen = 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(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1;
if(maxLen < dp[i][j])
maxLen = dp[i][j];
}
}
}
return maxLen * maxLen;
}
};