[LeetCode]221. Maximal Square
题目描述
思路
一种思路是直方图做法,可以解扩展到矩形的情况,见另一篇博客
[LeetCode]85. Maximal Rectangle
另外的思路是动态规划解法
给出的样例输入为
matrix | 0 | 1 | 2 | 3 | 4 |
---|---|---|---|---|---|
0 | 1 | 0 | 1 | 0 | 0 |
1 | 1 | 0 | 1 | 1 | 1 |
2 | 1 | 1 | 1 | 1 | 1 |
3 | 1 | 0 | 0 | 1 | 0 |
对应的状态矩阵
dp | 0 | 1 | 2 | 3 | 4 |
---|---|---|---|---|---|
0 | 1 | 0 | 1 | 0 | 0 |
1 | 1 | 0 | 1 | 1 | 1 |
2 | 1 | 1 | 1 | 2 | 2 |
3 | 1 | 0 | 0 | 1 | 0 |
代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int maximalSquare(vector<string>& matrix) {
if (matrix.size() == 0)
return 0;
int row = matrix.size(),
col = matrix[0].size(),
res = 0;
vector<vector<int>> dp(row, vector<int>(col));
for(int i = 0; i < row; ++i)
for (int j = 0; j < col; ++j) {
if (i == 0 || j == 0)
dp[i][j] = (matrix[i][j] == '1');
else if (matrix[i][j] == '0')
dp[i][j] = 0;
else {
int k = 1;
for (; k <= dp[i - 1][j - 1]; ++k)
if (dp[i - k][j] == 0 || dp[i][j - k] == 0)
break;
dp[i][j] = k;
}
res = max(res, dp[i][j]);
}
return res * res;
}
};
int main() {
vector<string> matrix = { "0010","1111","1111","1110","1100","1111","1110" };
Solution s;
cout << s.maximalSquare(matrix) << endl;
system("pause");
return 0;
}