436. Maximal Square
Tag:
Dynamic Problem.
Main Idea:
2D Matrix Rolling Array Problem. Let means the maximum square edge. The first thing to do is initialization, for all , and . The update equation is IF is true, then .
For optimization, we can reserve only two row for lookup, which would be row[i] and row[i-1].
Tips/Notes:
- In c++, min/max function can only compare two elements.
- and can be confusing sometimes. Note that the update equation uses as condition, but update .
- Finally, iterate the matrix, find the maximum and return the square of it.
Time/Space Cost:
Time Cost:
Space Cost:
,
for optimization.
Code:
class Solution {
public:
/**
* @param matrix: a matrix of 0 and 1
* @return: an integer
*/
int maxSquare(vector<vector<int>> &matrix) {
// write your code here]
int row = matrix.size();
int col = (row == 0)? 0 : matrix[0].size();
vector<vector<int>> dp(row, vector<int>(col,0) );
// initialization
for(int i = 0; i < row; i++){
dp[i][0] = matrix[i][0];
}
for(int j = 0; j < col; j++){
dp[0][j] = matrix[0][j];
}
// update dp[i][j]
for(int i = 1; i < row; i++){
for(int j = 1; j < col; j++){
if(matrix[i][j])
// note1 mentioned above
dp[i][j] = 1 + min(min(dp[i-1][j-1], dp[i-1][j]), dp[i][j-1]);
}
}
int ans = 0;
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
ans = max(ans, dp[i][j]);
}
}
return ans * ans;
}
};
Followup Problem:
- what if we want to get the maximum diagonal matrix, which the numbers on the diagonal are 1 only.
Main Idea:
Based on the original problem, the update equation would be: . Apparently, we need to maintain three matrix .
Time/Space Cost:
Time Cost:
Space Cost:
,
for optimization.