[LeetCode] Maximal Square
2015-06-06 14:31
288 查看
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.
更详细的解题思路见GeeksforGeeks。
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] = 0 2) 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; } };
相关文章推荐
- error: jemalloc/jemalloc.h: No such file or directory
- 分治法 --- 大整数的乘法
- 欢迎使用CSDN-markdown编辑器
- Variable shadowing
- DevExpress中GridControl中添加编辑按钮行
- 【php】php中的回调函数使用心得 - 2
- H2.64中I帧和IDR帧的区别
- XMPP学习总结
- 解决端口被占用而导致软件运行失败,程序无法启动,无法安装开发工具等问题
- ios 三级控制器 标签栏
- WinCE下开发程序常见问题
- 我的电脑(ACER 4750G)升级
- 25款最佳响应式前端开发框架
- 【VB.NET机房重构】编程注释
- 时间戳
- hdu 2049 不容易系列之(4)——考新郎
- 互联网搜索广告介绍(一)
- 父类引用指向子类对象
- 常用排序算法
- mysql忘记root密码怎么办