LeetCode: 221_Maximal Square | 二维0-1矩阵中计算包含1的最大正方形的面积 | Medium

时间:2021-09-17 17:01:18

题目:

Given a 2D binary matrix filled with 's and 1's, find the largest square containing all 's and return its area. 

For example, given the following matrix: 

Return . 

解题思路:

  这种包含最大、最小等含优化的字眼时,一般都需要用到动态规划进行求解。本题求面积我们可以转化为求边长,由于是正方形,因此可以根据正方形的四个角的坐标写出动态规划的转移方程式(画一个图,从左上角推到右下角,很容易理解):

dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1; where matrix[i][j] == 1

根据此方程,就可以写出如下的代码:

代码展示:

 #include <iostream>
#include <vector>
#include <cstring>
using namespace std; //dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1;
//where matrix[i][j] == 1
int maximalSquare(vector<vector<char>>& matrix)
{
if (matrix.empty())
return ; int rows = matrix.size();//行数
int cols = matrix[].size(); //列数 vector<vector<int> > dp(rows+, vector<int>(cols+, ));
/*
0 0 0 0 0 0
0 1 0 1 0 0
0 1 0 1 1 1
0 1 1 1 1 1
0 1 0 0 1 0
*/
int result = ; //return result for (int i = ; i < rows; i ++) {
for (int j = ; j < cols; j ++) {
if (matrix[i][j] == '') {
int temp = min(dp[i][j], dp[i][j+]);
dp[i+][j+] = min(temp, dp[i+][j]) + ;
}
else
dp[i+][j+] = ; result = max(result, dp[i+][j+]);
}
}
return result * result; //get the area of square;
} // int main()
// {
// char *ch1 = "00000";
// char *ch2 = "00000";
// char *ch3 = "00000";
// char *ch4 = "00000";
// vector<char> veccol1(ch1, ch1 + strlen(ch1));
// vector<char> veccol2(ch2, ch2 + strlen(ch2));
// vector<char> veccol3(ch3, ch3 + strlen(ch3));
// vector<char> veccol4(ch4, ch4 + strlen(ch4));
//
// vector<vector<char> > vecrow;
// vecrow.push_back(veccol1);
// vecrow.push_back(veccol2);
// vecrow.push_back(veccol3);
// vecrow.push_back(veccol4);
//
// vector<vector<char> > vec;
// cout << maximalSquare(vec);
// return 0;
// }