LeetCode:Maximal Square
来源:互联网 发布:淘宝模特多少钱一个月 编辑:程序博客网 时间:2024/06/13 19:49
Total Accepted: 25468 Total Submissions: 110270 Difficulty: Medium
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 01 0 1 1 11 1 1 1 11 0 0 1 0Return 4.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide Similar Problems
思路:
1.动态规划的题,可以维护一个ret[m*n]的整数数组去表示matrix各元素的状态;
2.首先边界i=0,j=0:第一行和第一列与matrix相同(即ret[i][0] = matrix[i][0],ret[0][i] = matrix[0][i]);
3.当i>0,j>0时,
如果matrix[i][j]=='0',ret[i][j]=0;
如果matrix[i][j]=='1',ret[i][j]由左上角的3个值推出;
推导公式,即状态转移方程为:ret[i][j]=min(ret[i-1][j],ret[i][j-1],ret[i-1][j-1]) + 1;
code:
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>> ret(m, vector<int>(n,0)); int maxSize = 0; for(int i=0;i<m;i++) { ret[i][0] = matrix[i][0]-'0'; maxSize = max(ret[i][0], maxSize); } for(int j=0;j<n;j++) { ret[0][j] = matrix[0][j]-'0'; maxSize = max(ret[0][j], maxSize); } for(int i=1;i<m;i++) for(int j=1;j<n;j++) { if(matrix[i][j]=='1') ret[i][j] = min(ret[i-1][j],min(ret[i][j-1],ret[i-1][j-1])) + 1; maxSize = max(ret[i][j], maxSize); } return maxSize*maxSize; }};
当然还可以有一些空间上的优化:Easy DP solution in C++ with detailed explanations (8ms, O(n^2) time and O(n) space)
0 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
- C++第一次实验成果
- hdu1561树形dp+依赖背包
- 性能测试指标之CPU时间片
- 华为oj 字串的连接最长路径查找
- 行内元素间距问题
- LeetCode:Maximal Square
- 我的书单
- JVM内存配置详解
- c++第一次实验-1
- 【基础篇】Apache相关问题汇总
- 获取中文字符长度遇到的问题,以及解决方法
- ASIHTTPRequest实现https双向认证请求
- PHP分页
- Xcode注释插件(一)