[LeetCode]221. Maximal Square
2017-04-19 10:56
465 查看
[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; }
相关文章推荐
- Leetcode 221. Maximal Square
- LeetCode 221. Maximal Square
- [LeetCode]problem 221. Maximal Square
- LeetCode 221. Maximal Square(最大正方形)
- Leetcode 221. Maximal Square
- 每周LeetCode算法题(八): 题目: 221. Maximal Square & 85. Maximal Rectangle
- leetcode 221. Maximal Square & 85. Maximal Rectangle
- LeetCode 221. Maximal Square
- 【Leetcode】221. Maximal Square
- Leetcode 221. Maximal Square
- LeetCode 85. Maximal Rectangle&221. Maximal Square--动态规划
- Leetcode 221. Maximal Square (Medium) (cpp)
- 221. Maximal Square LeetCode
- [LeetCode]221. Maximal Square
- **Leetcode 221. Maximal Square | dp
- LeetCode221. Maximal Square
- 求解最大正方形面积 — leetcode 221. Maximal Square
- LeetCode *** 221. Maximal Square
- leetcode 221. Maximal Square 最大正方形面积 + 动态规划DP实现
- [leetcode]221. Maximal Square