1. 程式人生 > >leetcode 85. Maximal Rectangle 最大矩形

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;
    }
};