【LeetCode】—— 最大矩形
给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
示例 1:

输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:6
解释:最大矩形如上图所示。
1 class Solution { 2 public int maximalRectangle(char[][] matrix) { 3 // 对每一列进行单调栈的计算 4 int row = matrix.length; 5 if(row < 1){ 6 return 0; 7 } 8 int col = matrix[0].length; 9 // 对每一列计算其左边一栏的连续的1的个数 10 int [][]left = new int[row][col]; 11 for(int i=0;i<row;i++){ 12 for (int j =0;j<col;j++){ 13 if (matrix[i][j]=='1'){ 14 left[i][j] = j==0?1:left[i][j-1]+1; 15 } 16 } 17 } 18 int ret =0; 19 // 遍历每一列 20 for(int j =0;j<col;j++){ 21 // 对每一行从上往下进行单调栈 22 int []ups = new int[row]; 23 Deque<Integer> stack = new ArrayDeque<>(); 24 for(int i=0;i<row;i++){ 25 // 一定要大于等于,否则找不到更小的位置 26 while (!stack.isEmpty() && left[stack.peek()][j] >= left[i][j]){ 27 stack.pop(); 28 } 29 // 更新比当前位置更小的位置 30 ups[i]= stack.isEmpty()?-1:stack.peek(); 31 stack.push(i); 32 } 33 // 清空栈 34 stack.clear(); 35 int[] downs = new int[row]; 36 for(int i=row-1;i>=0;i--){ 37 while(!stack.isEmpty() && left[stack.peek()][j] >= left[i][j]){ 38 stack.pop(); 39 } 40 downs[i] = stack.isEmpty()?row:stack.peek(); 41 stack.push(i); 42 } 43 for(int i=0;i<row;i++){ 44 int height = left[i][j]; 45 ret = Math.max(ret,height*(downs[i]-ups[i]-1)); 46 } 47 } 48 return ret; 49 } 50 }
解题关键:
1.单调栈。
2.记录每一列左边的连续的1的个数,包括本身。
3.对每一列当成逆时针旋转90度的柱状图,求最大的矩形面积。

浙公网安备 33010602011771号