Maximal Square
2016-09-07 09:19
176 查看
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.
Example
For example, given the following matrix:
Return
Analyse: Let dp[i][j] represents the maximum side of a square whose right bottom element is matrix[i][j].
Runtime: 124ms
Example
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.
Analyse: Let dp[i][j] represents the maximum side of a square whose right bottom element is matrix[i][j].
dp[i][j] = min(dp[i][j - 1], min(dp[i - 1][j], dp[i - 1][j - 1])) + 1
Runtime: 124ms
class Solution { public: /** * @param matrix: a matrix of 0 and 1 * @return: an integer */ int maxSquare(vector<vector<int> > &matrix) { // write your code here if (matrix.empty() || matrix[0].empty()) return 0; int m = matrix.size(), n = matrix[0].size(); vector<vector<int> > dp(m, vector<int>(n, 0)); int result = 0; // initialize the first row for (int i = 0; i < n; i++) { if (matrix[0][i]) { dp[0][i] = 1; result = 1; } } // initialize the first column for (int i = 0; i < m; i++) { if (matrix[i][0]) { dp[i][0] = 1; result = 1; } } // calculate the remaining part for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if (matrix[i][j]) { dp[i][j] = min(dp[i][j - 1], min(dp[i - 1][j], dp[i - 1][j - 1])) + 1; result = max(result, dp[i][j]); } else dp[i][j] = 0; } } return result * result; } };
相关文章推荐
- MongoDB系列三:Replica Sets在生产环境中安装配置的注意事项
- Linux下Tomcat重新启动
- Struts2体系结构图以及详解
- 解决:Connections could not be acquired from the underlying database!
- iOS开发网络篇—发送GET和POST请求(使用NSURLSession)
- firefox 28.0
- sql查询语句
- 160906--LLCR算法
- 机器学习算法6-AdaBoost元算法
- 诡异的异常SEVERE: Error creating form bean of class
- 自定义View练习一之图片以及标题随手势方向平滑加载
- Webpack从入门到上线
- eclipse neno中tomcat配置servers locations地址的文件
- 辰辰的成长记录
- 【BZOJ】1596: [Usaco2008 Jan]电话网络
- java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener问题
- BZOJ3142 [Hnoi2013]数列
- TCP/IP之八:广播、多播与IGMP
- WaitForMultipleObjects用法详解,一看就懂
- Digimat-MF:均匀化和尺度转换方法