[LeetCode] Maximal Square
来源:互联网 发布:windows phone下载软件 编辑:程序博客网 时间:2024/05/16 10:01
Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing all 1’s and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 4.
解题思路
1) Construct a sum matrix S[R][C] for the given M[R][C]. a) Copy first row and first columns as it is from M[][] to S[][] b) For other entries, use following expressions to construct S[][] If M[i][j] is 1 then S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1 Else /*If M[i][j] is 0*/ S[i][j] = 02) Find the maximum entry in S[R][C]3) Using the value and coordinates of maximum entry in S[i], print sub-matrix of M[][]
更详细的解题思路见GeeksforGeeks。
实现代码
class Solution {public: int maximalSquare(vector<vector<char>>& matrix) { if (matrix.empty()) { return 0; } int row = matrix.size(); int col = matrix[0].size(); vector<vector<int>> s(row, vector<int>(col, 0)); for (int i = 0; i < row; i++) { if (matrix[i][0] == '1') { s[i][0] = 1; } } for (int i = 0; i < col; i++) { if (matrix[0][i] == '1') { s[0][i] = 1; } } for (int i = 1; i < row; i++) { for (int j = 1; j < col; j++) { if (matrix[i][j] == '1') { s[i][j] = min(s[i-1][j], min(s[i][j-1], s[i-1][j-1])) + 1; } else { s[i][j] = 0; } } } int width = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { width = max(width, s[i][j]); } } return width * width; }};
1 0
- 【LeetCode】Maximal Rectangle && Maximal Square
- Leetcode:Maximal Square & Maximal Rectangle
- [leetcode] Maximal Square
- Maximal Square Leetcode Java
- [leetcode] Maximal Square
- leetcode 221: Maximal Square
- LeetCode Maximal Square
- Maximal Square - LeetCode 221
- #leetcode#Maximal Square
- LeetCode Maximal Square
- [LeetCode] Maximal Square
- [LeetCode]Maximal Square
- leetcode Maximal Square
- leetcode Maximal Square
- Leetcode 221 Maximal Square
- leetCode(27):Maximal Square
- [leetCode] Maximal Square
- Leetcode 221 Maximal Square
- java之list源码浅析
- 牌具系列绝对好任性出众手表镜头
- DevExpress中GridControl中添加编辑按钮行
- iOS 8 AutoLayout与Size Class
- hdu 2005 第几天?
- [LeetCode] Maximal Square
- XMPP学习总结
- 2015主打深圳牌具产品TTK---三星note3隆重上市
- VC基础教程
- error: jemalloc/jemalloc.h: No such file or directory
- 欢迎使用CSDN-markdown编辑器
- 2015最新作品强势来袭苹果6S手机镜头
- 窗口和控件闪烁解决方案
- 第十四周项目1——(2)