Maximal Rectangle

51 篇文章 0 订阅
18 篇文章 0 订阅

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

思路: First, we storage the width of every nodes. Then, we traverse the whole board and every time we move up to find the min Width to times the height. After that, we compare the max area.
先遍历整个矩阵, 设置好每个点向左边的最大宽度。 然后再次遍历, 每遇到一个 1 , 从当前点向上, 每次都使用最窄的宽度, i + 1 - curI 是高度, 然后比较获得最大面积。 

易错点: 刚开始时候 只考虑 j == 0 就行,千万别考虑 i == 0;
取窄边时候 要记住用 curI , width[curI][j];
要找宽度最窄的乘以 (i - minWidth + 1 来获得面积。
别忘记minI--;

public class Solution {
	
	public int maximalRectangle(char[][] matrix) {
		int m = matrix.length;
		if(m == 0){
			return 0;
		}
		int n = matrix[0].length;
		int max = 0;
		int[][] width = new int[m][n];
		for(int i = 0; i < m; i++){
		    for(int j = 0; j < n; j++){
		       if(matrix[i][j] == '1'){
		           if(j == 0){// --
		               width[i][j] = 1;
		           }else{
		               width[i][j] = width[i][j-1] + 1;
		           }
		       } 
		    }
		}
		for(int i = 0; i < m; i++){
		    for(int j = 0; j < n; j++){
		        if(matrix[i][j] == '1'){
		            int curI = i;
		            int minWidth = width[i][j];
		            while(curI >= 0){
		                minWidth = Math.min(minWidth, width[curI][j]);// --
		                max = Math.max(max, minWidth * (i + 1 - curI));
		                curI--;//--
		            }
		        }
		    }
		}
        return max;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值