题目描述:
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.
思路:以每行分别作为柱状图的最底行来求最大面积。和Largest_Rectangle_in_Histogram一个思路。
public class Maximal_Rectangle {
//line是以第line行作为柱状图的最底行,column是第column列该列柱图的高度,matrix是给定的矩阵.
public static int getHeight(int line,int column,char[][] matrix)
{
if(matrix[line][column]=='0')
return 0;
int height = 1;
for(int i=line-1;i>=0;i--)
{
if(matrix[i][column]=='0')
break;
height++;
}
return height;
}
public static int maximalRectangle(char[][] matrix)
{
if(matrix==null||matrix.length==0||matrix[0].length==0)
return 0;
int Maxarea = 0;
//存放的是每列的高度
int heights[] = new int[matrix[0].length];
for(int i=0;i<matrix.length;i++)
{
//存放的是序列的下标
Stack<Integer> stack = new Stack<Integer>();
int area = 0;
for(int j=0;j<matrix[0].length;j++)
{
heights[j] = getHeight(i, j, matrix);
while(!stack.isEmpty()&&heights[j]<heights[stack.peek()])
{
int index = stack.pop();
int height = heights[index];
//这里减去stack.peek()-1,是因为要将前面比该数大但是在该数入栈之前就已经出栈的柱型也算上
//j-stack.peek()-1就是上一个比该数小的数到该数的距离
int width = stack.isEmpty()?j:(j-stack.peek()-1);
area = Math.max(area,height*width);
}
stack.push(j);
}
while(!stack.isEmpty())
{
int index = stack.pop();
int height = heights[index];
//这里减去stack.peek()-1,是因为要将前面比该数大但是在该数入栈之前就已经出栈的柱型也算上
//j-stack.peek()-1就是上一个比该数小的数到该数的距离
int width = stack.isEmpty()?matrix[0].length:(matrix[0].length-stack.peek()-1);
area = Math.max(area,height*width);
}
Maxarea = Math.max(Maxarea, area);
}
return Maxarea;
}
public static void main(String[] args) {
char matrix[][] = {{'1','0','1','0','0'},{'1','0','1','1','1'},{'1','1','1','1','1'},{'1','0','0','1','0'}};
System.out.println(maximalRectangle(matrix));
}
}