LeetCode Maximal Rectangle

本文讨论了如何在二维二进制矩阵中找到包含全部1的最大矩形区域,并计算其面积。通过将矩阵转换为高度数组,利用直方图最大矩形面积的解决方法来实现。

Description:

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

Solution:

This problem is very close to the last problem: largest rectangle in histogram. And all we have to do here is to try to convert this 0 and 1 2D matrix to a n height arrays. Then for each array, we can calculate a max rectangle area.


import java.io.*;
import java.util.*;


class Solution {
  
  public static void main(String[] args){
    Solution s = new Solution();
    int arr[]={1,2,3};
    System.out.println(s.largestRectangleArea(arr));
  }
  
  public int largestRectangleArea(int[] height) {
    if(height==null)
      return 0;
    int n = height.length;
    int h[] = new int[n+1];
    h = Arrays.copyOf(height, n+1);
    
    int max=0;
    
    Stack<Integer> stack = new Stack<Integer>();
    int i =0;
    while(i<=n){
      if(stack.isEmpty()||h[stack.peek()]<h[i]){
        stack.push(i);
        i++;
      }else{
        int t = stack.pop();
        int ta;
        if (stack.isEmpty())
          ta = i * h[t];
        else
          ta = (i - stack.peek() - 1) * h[t];
        max = Math.max(max, ta);
      }
    }
    
    return max;
  }
  
  public int maximalRectangle(char[][] matrix) {
      if(matrix==null||matrix.length==0)
      return 0;
    int n = matrix.length;
    int m = matrix[0].length;
    
    int height[] = new int[m];
    
    int max_area = 0;
    
    for (int i=0;i<n;i++){
      for (int j=0;j<m;j++)
        if(matrix[i][j]=='0')
          height[j] = 0;
      else
        height[j] += 1;
      
      max_area = Math.max(max_area, largestRectangleArea(height));
    }
    
    return max_area;
  }
  
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值