您的位置:首页 > 其它

[LeetCode]221. Maximal Square

2017-04-19 10:56 465 查看

[LeetCode]221. Maximal Square

题目描述



思路

一种思路是直方图做法,可以解扩展到矩形的情况,见另一篇博客

[LeetCode]85. Maximal Rectangle

另外的思路是动态规划解法

给出的样例输入为

matrix01234
010100
110111
211111
310010
对应的状态矩阵

dp01234
010100
110111
211122
310010

代码

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: