Maximal Rectangle

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

如果用DP来做,判断(begin1,end1)~(begin2,end2)范围是否全1,会超时。

对于矩阵matrix,逐行构建height数组,调用Largest Rectangle in Histogram即可。

对matrix第i行构建height数组方法:对于height[j],即从matrix[i][j]开始,最多到达matrix[0][j]的连续1个数。

class Solution {
public: int maximalRectangle(vector<vector<char> > &matrix) {
int ret = ;;
if(matrix.empty() || matrix[].empty())
return ret;
int m = matrix.size();
int n = matrix[].size();
for(int i = ; i < matrix.size(); i ++)
{
vector<int> height(n, );
for(int j = ; j < n; j ++)
{
int r = i;
while(r >= && matrix[r][j] == '')
{
height[j] ++;
r --;
}
}
ret = max(ret, largestRectangleArea(height));
}
return ret;
} int largestRectangleArea(vector<int> &height) {
if(height.empty())
return ; int result = ;
stack<int> s; //elements in stack s are kept in ascending order
int ind = ;
while(ind < height.size())
{
if(s.empty() || height[ind]>=s.top())
{
s.push(height[ind]);
}
else
{
int count = ; //pop count
while(!s.empty() && height[ind]<s.top())
{
int top = s.top();
s.pop();
count ++;
result = max(result, count*top);
}
for(int i = ; i <= count; i ++)
s.push(height[ind]); //push count+1 times
}
ind ++;
}
//all elements are in stack s, and in ascending order
int count = ;
while(!s.empty())
{
count ++;
int top = s.top();
s.pop();
result = max(result, count*top);
} return result;
}
};

最新文章

  1. Xamarin.Forms.Platform.Perspex, Xamarin Forms 的 Perspex(号称下一代WPF) 实现
  2. ubuntu qq
  3. [ios][swift]swift GPS传感器的调用
  4. 使用OmniGraffle制作原型图
  5. C# 打印异常
  6. Oracle PL/SQL 找出100以内是3和5的倍数的数 循环语句
  7. Emmet(前身是zen coding)介绍和使用
  8. ViewPager.getChildCount() 含义
  9. Linux最佳的云存储服务分析
  10. vue的环境安装(一node环境)
  11. MySQL data sync to Oracle with OGG(Remote Delivery)
  12. 2.Swift快速浏览
  13. String[]与List&lt;String&gt;的相互转换
  14. ES6 Symbol的应用场景
  15. 【Python】TypeError: a bytes-like object is required, not &#39;str&#39;解决
  16. vector读入指定行数但不指定列数的数字
  17. 6个原则、50条秘技提高HTML5应用及网站性能
  18. 一段有用的javascript加密解密
  19. asp 支付宝 企业版 接口 支持网银接口 ,网银直接支付
  20. ASP.NET Core 2.2 基础知识(五) 环境

热门文章

  1. React Native中树 TreeView 实现(2)
  2. mysql内存参数整理和条调优以及内存统计
  3. eclipse.ini 文件使用说明
  4. ubuntu上安装systemtap
  5. GCC安装UBUNTU
  6. WebService如何抛出干净的异常
  7. 【提醒】使用 iptables 时,特别注意 规则的顺序
  8. Codeforces Round #261 (Div. 2)[ABCDE]
  9. linux下的springboot项目启动文件
  10. SQL VM上磁盘延迟高, 但Host和Storage Array上的延迟却很低的问题