221. Maximal Square
Problem description:
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:1
2
3
4
5
6
7
8Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
solution1:
time: O(mn)
space: O(mn)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int m = matrix.size(), n = m>0 ? matrix[0].size(): 0;
vector<vector<int>> dp(m+1, vector<int>(n+1, 0));
int maxlen = 0;
for(int i = 1; i<= m; ++i){
for(int j= 1; j<= n; ++j){
if(matrix[i-1][j-1] == '1'){
dp[i][j] = min(dp[i][j-1], min(dp[i-1][j], dp[i-1][j-1])) +1;
maxlen = max(maxlen, dp[i][j]);
}
}
}
return maxlen*maxlen;
}
};
solution2:
time: O(mn)
space: O(n)
dp[j] is to store the square that can be made in this1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int m = matrix.size(), n = m>0 ? matrix[0].size(): 0;
vector<int> dp(n+1, 0);
int maxlen = 0, prev= 0;
for(int i = 1; i<= m; ++i){
for(int j= 1; j<= n; ++j){
int temp = dp[j];
//cout<< "dp["<<j<<"]:"<<dp[j]<<endl;
//cout<<"temp:"<< temp<<endl;
if(matrix[i-1][j-1] == '1'){
dp[j] = min(dp[j-1], min(prev, dp[j]))+1;
//+1 is because if this element is '1', it at least can form a square by itself even previous is 0
//cout<< "dp["<<j<<"-1]:"<<dp[j-1];
//cout<< ", prev:"<<prev;
//cout<< ", dp["<<j<<"]:"<<dp[j]<<endl;
//dp[i][j] = min(dp[i][j-1], min(dp[i-1][j], dp[i-1][j-1])) +1;
maxlen = max(maxlen, dp[j]);
//cout<<"max="<<maxlen<<endl;
}
else{
dp[j] = 0;
//cout<< "else dp["<<j<<"]:"<<dp[j]<<endl;
}
prev= temp;
//cout<<"----"<<endl;
}
}
for(auto n: dp)
cout<<n<<" "<<endl;
return maxlen*maxlen;
}
};