leetcode 85. Maximal Rectangle 最大矩形

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

Example:

Input:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
Output: 6

如果解决了 84.Largest Rectangle in Histogram(我的上一篇博客)

那么这个题很简单,照着上一篇的思路,改造一下就可以了 20ms

struct histogram{
	int height;
	int id;
	histogram(){}
	histogram(int h,int i)
	{
		this->height=h;
		this->id=i;
	}
};

class Solution{
private:
	int h[405][405];
	int result;
public:
	void init_height(vector<vector<char>>& matrix,int n,int m)
	{
		result=0;
		for(int j=0;j<m;++j)
		{
			if(matrix[0][j]=='1')
				h[0][j]=1;
			else
				h[0][j]=0;
		}
		for(int i=1;i<n;++i)
		{
			for(int j=0;j<m;++j)
			{
				if(matrix[i][j]=='1')
					h[i][j]=h[i-1][j]+1;
				else
					h[i][j]=0;
			}
		}
	}
	void calc_area_line(int x,int m)
	{
		stack<histogram> s;
		s.push(histogram(h[x][0],0));
		int now_height;
		for(int i=1;i<=m;++i)
		{
			if(i==m)
				now_height=-1;
			else
				now_height=h[x][i];
			if(now_height>=s.top().height)
				s.push(histogram(now_height,i));
			else
			{
				while(true)
				{
					if(s.empty() || now_height>=s.top().height)
					{
						s.push(histogram(now_height,i));
						break;
					}
					int h1=s.top().height,id1=s.top().id;
					int area1=h1*(i-id1);s.pop();
					if(s.empty())
					{
						int area2=h1*id1;
						result=max(result,area1+area2);
					}
					else
					{
						int id2=s.top().id;
						int area2=h1*(id1-id2-1);
						result=max(result,area1+area2);
					}
				}
			}
		}
	}
    int maximalRectangle(vector<vector<char>>& matrix)
	{
		int n=matrix.size();
		if(n==0)
			return 0;
		int m=matrix[0].size();
		if(m==0)
			return 0;
		init_height(matrix,n,m);
		for(int i=0;i<n;++i)
			calc_area_line(i,m);
		return this->result;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值