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>& matrix,int n,int m)
	{
		result=0;
		for(int j=0;j 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>& 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;iresult;
    }
};

 

你可能感兴趣的:(杂题,数据结构)