|
| 1 | +package leetCode.subject.number51_100; |
| 2 | + |
| 3 | +import java.util.Stack; |
| 4 | + |
| 5 | +/** |
| 6 | + * @author : CodeWater |
| 7 | + * @create :2022-08-13-23:45 |
| 8 | + * @Function Description :85.最大矩形 |
| 9 | + */ |
| 10 | +public class _85MaximumRectangle { |
| 11 | + class Solution { |
| 12 | + /**变种:找正方形 |
| 13 | + 找矩形:枚举(需要优化) |
| 14 | + 做法: 找一个下边界,然后基于这个下边界变成上一题的柱状图(每一个位置找出往上连续的1),然后求柱状图的最大矩形 |
| 15 | + h(i,j):由位置i往上连续j个位置都是连续的1的个数。递推求得,该位置是0值为0;不是0,由当前位置1加上位置上面一个位置的值即可。 |
| 16 | +
|
| 17 | + */ |
| 18 | + int largestRectangleArea(int[] h){ |
| 19 | + int n = h.length ; |
| 20 | + int[] left = new int[n] , right = new int[n]; |
| 21 | + Stack<Integer> stk = new Stack<>(); |
| 22 | + |
| 23 | + for( int i = 0 ; i < n ; i++ ){ |
| 24 | + while( stk.size() > 0 && h[stk.peek()] >= h[i] ) stk.pop(); |
| 25 | + if( stk.size() > 0 ) left[i] = stk.peek(); |
| 26 | + else left[i] = -1; |
| 27 | + stk.push( i ); |
| 28 | + } |
| 29 | + |
| 30 | + stk.clear(); |
| 31 | + for( int i = n - 1 ; i >= 0 ; i-- ){ |
| 32 | + while( stk.size() > 0 && h[stk.peek()] >= h[i] ) stk.pop(); |
| 33 | + if( stk.size() > 0 ) right[i] = stk.peek(); |
| 34 | + else right[i] = n ; |
| 35 | + stk.push(i); |
| 36 | + } |
| 37 | + |
| 38 | + int ans = 0 ; |
| 39 | + for( int i = 0 ; i < n ; i++ ){ |
| 40 | + ans = Math.max( ans , h[i] * (right[i] - left[i] - 1 ) ); |
| 41 | + } |
| 42 | + |
| 43 | + return ans; |
| 44 | + } |
| 45 | + |
| 46 | + |
| 47 | + public int maximalRectangle(char[][] matrix) { |
| 48 | + int n = matrix.length , m = matrix[0].length; |
| 49 | + if( n == 0 || m == 0 ) return 0; |
| 50 | + |
| 51 | + // 初始化h[i][j]:表示以(i,j)为底的连续1的高度(转换成柱状图) |
| 52 | + int[][] h = new int[n][m]; |
| 53 | + for( int i = 0 ; i < n ; i++ ){ |
| 54 | + for( int j = 0 ; j < m ; j++ ){ |
| 55 | + if( matrix[i][j] == '1' ){ |
| 56 | + if( i > 0 ) h[i][j] = h[i - 1][j] + 1; |
| 57 | + else h[i][j] = 1; |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + int ans = 0; |
| 63 | + // 遍历每一行,求出最大矩形 |
| 64 | + for( int i = 0 ; i < n ; i++ ){ |
| 65 | + // largestRectangleArea求柱状图的最大矩形,这里对于二维数组来说,传一行就是以这一行作为柱状图的底 |
| 66 | + ans = Math.max( ans , largestRectangleArea(h[i]) ); |
| 67 | + } |
| 68 | + |
| 69 | + return ans; |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments