题目:
Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.
思路:
动态规划。公式为:dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
。dp数组的首行或首列与matrix相同。dp[i][j]意思是以(i,j)为右下角的最大正方形的边长。
举个例子说明dp[i][j]的求解过程(即动态规划公式)。例如,dp[i][j]从1升3的所有情况如下:
Example中的dp数组值如下:
代码实现:
class Solution {
public:
int min(int a, int b, int c){
int t = INT_MAX;
if (a < t){
t = a;
}
if (b < t){
t = b;
}
if (c < t){
t = c;
}
return t;
}
int maximalSquare(vector<vector<char>>& matrix) {
if (matrix.size() <= 0 || matrix[0].size() <= 0){
return 0;
}
int rows = matrix.size();
int cols = matrix[0].size();
vector<vector<int>> dp(rows, vector<int>(cols, 0));
int ret = INT_MIN;
for (int i = 0; i < rows; ++i){
for (int j = 0; j < cols; ++j){
if (i == 0 || j == 0 || matrix[i][j] == '0'){
dp[i][j] = matrix[i][j] - '0';
}else{
dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1;
}
ret = max(ret, dp[i][j]);
}
}
return ret*ret;
}
};