算法练习帖--40--最大矩形(Java)

最大矩形

一、题目简介

给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
题目来源:leetcode题号85
柱状图中最大的矩形:leecode题号84博客
注:是leecode题号84的升级版,思路差不多,这题需要转化而已。
示例 1:
在这里插入图片描述

输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:6
解释:最大矩形如上图所示
示例 2:
输入:matrix = []
输出:0
示例 3:
输入:matrix = [["0"]]
输出:0
示例 4:
输入:matrix = [["1"]]
输出:1
示例 5:
输入:matrix = [["0","0"]]
输出:0
提示:
rows == matrix.length
cols == matrix[0].length
0 <= row, cols <= 200
matrix[i][j] 为 '0' 或 '1'

二、解决方法

1. 多层循环+单层贪心

package com.lxf.test;

public class MaximalRectangle {
    
    
    public static void main(String[] args) {
    
    
        char[][] chars=new char[][]{
    
    {
    
    '1','0','1','0','0'},{
    
    '1','0','1','1','1'},{
    
    '1','1','1','1','1'},{
    
    '1','0','0','1','0'}};
        System.out.println(maximalRectangle(chars));
    }
    /**
	*按每列绘制出每一个柱状图数组,
	*用largestRectangleArea求出每个柱状图的最大值
	*求得每个柱状图的最大值的最大值即可
	*/
    public static int maximalRectangle(char[][] matrix) {
    
    
    	//行数
        int rows=matrix.length;
        //排除matrix数组为空的情况
        if(rows==0){
    
    
            return 0;
        }
        //列数
        int cols=matrix[0].length;
        //最大面积
        int maxArea=0;
        int[] heights = new int[rows];
        //遍历每一列
        for (int i = 0; i < cols; i++) {
    
    
        	//遍历每一行,求出当前列每一行的最大柱,用heights存储得到柱状图
            for (int j = 0; j < rows; j++) {
    
    
                int height=0;
                while((height+i)<cols&&matrix[j][height+i]=='1'){
    
    
                    height++;
                }
                heights[j]=height;
            }
            //获取每一个柱状图中面积的最大值的最大值
            maxArea=Math.max(maxArea, largestRectangleArea(heights));
        }
        return maxArea;
    }
	/**
	*求每个柱状图的最大矩形
	*/
    public static int largestRectangleArea(int[] heights) {
    
    
        int maxArea=0;
         //遍历数组的每一个值
        for (int i = 0; i < heights.length; i++) {
    
    
            int curArea=heights[i];
            int j=i;
            int k=i;
            //当前数字向右搜索比它大的最后一个数字的下标
            while(j<heights.length&&curArea<=heights[j]){
    
    
                j++;
            }
            //当前数字向左搜索比它大的最后一个数字的下标
            while(k>=0&&curArea<=heights[k]){
    
    
                k--;
            }
            //两下标相减再减1乘以当前数字就是矩形的面积了,记录每个面积的最大值
            maxArea=Math.max(maxArea, (j-k-1)*heights[i]);
        }
        return maxArea;
    }
}

2.更多解法:链接

猜你喜欢

转载自blog.csdn.net/Inmaturity_7/article/details/111793559