221.Maximal Square
2015-06-30 15:22
232 查看
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:
Return 4.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
https://leetcode.com/discuss/38489/easy-solution-with-detailed-explanations-8ms-time-and-space
P[i][j]表示在点(i,j)处,可以得到的最大正方形的边长。
For
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.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
https://leetcode.com/discuss/38489/easy-solution-with-detailed-explanations-8ms-time-and-space
P[i][j]表示在点(i,j)处,可以得到的最大正方形的边长。
P[0][j] = matrix[0][j](topmost row);
P[i][0] = matrix[i][0](leftmost column);
For
i > 0and
j > 0: if
matrix[i][j] = 0,
P[i][j] = 0; if
matrix[i][j] = 1,
P[i][j] = min(P[i - 1][j], P[i][j - 1], P[i - 1][j - 1]) + 1.
class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { int m = matrix.size(); if(m == 0) return 0; int n = matrix[0].size(); vector<vector<int>> P(m,vector<int>(n,0)); int maxSize = 0; for(int i = 0;i<m;i++) { P[i][0] = matrix[i][0]-'0'; maxSize = max(maxSize,P[i][0]); } for(int j = 0;j<n;j++) { P[0][j] = matrix[0][j]-'0'; maxSize = max(maxSize,P[0][j]); } for(int i = 1;i<m;i++) { for(int j = 1;j<n;j++) { if(matrix[i][j] == '1') { P[i][j] = min(P[i-1][j-1],min(P[i-1][j],P[i][j-1]))+1; maxSize = max(maxSize,P[i][j]); } } } return maxSize * maxSize; } };
相关文章推荐
- beaglebone black tftp与nfs挂载根文件系统
- Hadoop的fsck工具
- hadoop升级之fsck命令迎战miss block警告
- 安卓的数据存取(file)
- mac 命令行打开app
- 使用VLC进行屏幕广播
- nc 局域网聊天+文件传输(netcat)
- Android务虚之MVC
- SQL2008 创建定时任务作业
- android ImageView scaleType属性
- 地形细节纹理
- 抽象语法分析树的好文章
- WebService(2)-XML系列之用Stax操作Xml
- Fragment FragmentManager FragmentTransaction 详解
- 第三方登录流程图
- Android 百分比布局库(percent-support-lib) 解析与扩展
- 流媒体(音频 AudioStreamer)
- Android 百分比布局库(percent-support-lib) 解析与扩展
- DRBD+HeartBeat+NFS:配置NFS的高可用 推荐
- 解决Fragment中使用map,切换会闪一下黑屏的有关问题