实现的完整代码如下:
import java.util.Stack;
//获得给定矩阵的最大子矩阵
public class MaxSubMatrix{
public static int getMaxSubMatrix(int[][]map)
{
if(map==null||map.length==0||map[0].length==0)
{
return 0;
}
int maxArea=0; //记录矩形区域的面积
int []height=new int[map[0].length]; //记录矩形的高度
for(int i=0;i<map.length;i++)
{
for(int j=0;j<map[0].length;j++)
{
height[j]=map[i][j]==0 ?0:height[j]+1; //计算出每个矩形的高度
}
maxArea=Math.max(maxRecFromBottom(height),maxArea);
}
return maxArea;
}
//利用栈计算区域面积的大小
public static int maxRecFromBottom(int[]height)
{
if(height==null || height.length==0)
{
return 0;
}
int maxArea=0;
Stack <Integer>stack=new Stack<Integer>();
for(int i=0;i<height.length;i++)
{
while(!stack.isEmpty()&&height[i]<=height[stack.peek()])
{
int j=stack.pop();
int k=stack.isEmpty()?-1:stack.peek();
int curArea=(i-k-1)*height[j]; //计算当前区域的面积
maxArea=Math.max(maxArea,curArea);
}
stack.push(i); //当前数大于栈顶的数压栈
}
while(!stack.isEmpty())
{
int j= stack.pop();
int k=stack.isEmpty()?-1:stack.peek();
int curArea=(height.length-k-1)*height[j]; //计算区域面积的公式
maxArea=Math.max(maxArea,curArea);
}
return maxArea;
}
public static void main(String[]args)
{
//int[][]map={{1,0,1,1},{1,1,1,1},{1,1,1,0}};
int[][]map={{1},{1},{1},{0}}; //单行测试
System.out.println(getMaxSubMatrix(map));
}
}