LeetCode解题笔记 20 —— 85. 最大矩形

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m940034240/article/details/89337773

题目

给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

示例:

输入:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
输出: 6

解法

引用了第84题  柱状图中最大的矩形的解法   LeetCode解题笔记 19 —— 84. 柱状图中最大的矩形

class Solution {
    public int maximalRectangle(char[][] matrix) {
        int s = 0;
        if(matrix == null){
            return s;
        }
        //逐行判断最大面积
        for(int i = 0; i < matrix.length; i++){
            int[] heights = new int[matrix[i].length];
            for(int j = 0; j < matrix[i].length; j++){
                int count = 0;//以当前行为底边的高度
                for(int k = i; k  < matrix.length; k++){
                   if(matrix[k][j]=='1'){
                       count++;
                   }else{
                       break;
                   }
                }
                heights[j] = count;
            }
            int m =  largestRectangleArea(heights);
            if(m > s){
                s = m;
            }
        }
        return s;
    }
    public int largestRectangleArea(int[] heights) {
        int max = 0;
        for(int i = 0; i < heights.length; i++){
            int h = Integer.MAX_VALUE;
            for(int j = i;j < heights.length; j++){
                if(heights[j] < h){
                    h = heights[j];
                }
                int s = h * (j - i +1);
                if(s > max){
                    max = s;
                }
            }
        }
        return max;
    }
}

猜你喜欢

转载自blog.csdn.net/m940034240/article/details/89337773
今日推荐