【直方图面积】Maximal Rectangle

来源:互联网 发布:舞台灯光编程软件 编辑:程序博客网 时间:2024/05/29 06:49

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

思路转自:http://blog.csdn.net/havenoidea/article/details/11876165

题意有一个01组成的矩阵,找到其中面积最大的,全部由1构成的子矩阵。

去年做多校比赛的时候第一次见到这题,不优化到O(n×n)死活过不了当时。

优化就是先预处理成保存成,当前点向上都是1的最高的高度,就变成每一行都是一个直方图

然后使用求直方图面积的算法

public class Solution {    public int maximalRectangle(char[][] m) {        if(m==null || m.length == 0)return 0;        int row = m.length;        int col = m[0].length;        int h[][] = new int[row][col+1];                for(int i=0; i<row; i++){            for(int j=0; j<col; j++){                if(m[i][j] == '0') h[i][j] = 0;                else if(i==0){                    h[i][j] = 1;                }                else{                    h[i][j] = h[i-1][j] + 1;                }            }        }                int area=0;        for(int i=0; i<row; i++){            Stack<Integer> s = new Stack<Integer>();            int j=0;            while(j<=col){                if(s.isEmpty() || h[i][j] >= h[i][s.peek()]){                    s.push(j++);                }                else{                    int t = s.pop();                    int tArea = h[i][t] * (s.isEmpty() ? j : j-s.peek()-1);                    area = Math.max(area, tArea);                }            }        }        return area;    }}


0 0
原创粉丝点击