LeetCode 85. Maximal Rectangle

来源:互联网 发布:新加坡apache国际集团 编辑:程序博客网 时间:2024/06/06 07:24

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

For example, given the following matrix:

1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0

Return 6.

在一个矩阵里 找到面积最大的 由1构成的矩阵,这题想了很久没想出办法,看了code ganker的博客,发现其实和上一道题是一样的,以每一行为底,求由该行为底能构成的最大矩阵。

public class Solution {    public int maximalRectangle(char[][] matrix) {        if(matrix.length==0||matrix[0].length==0)return 0;        int res = 0;        int dp[] = new int[matrix[0].length];        for(int i=0;i<matrix.length;i++){            for(int j=0;j<matrix[0].length;j++){                dp[j] = matrix[i][j]=='0'?0:dp[j]+1;            }            res = Math.max(res,helper(dp));        }        return res;    }    public int helper(int dp[]){        if(dp.length==0)return 0;        int m = 0;        Stack<Integer>s = new Stack<Integer>();        for(int i=0;i<dp.length;i++){            while(!s.isEmpty()&&dp[i]<=dp[s.peek()]){                int index = s.pop();                m = Math.max(m,s.isEmpty()?dp[index]*i:dp[index]*(i-s.peek()-1));            }            s.push(i);        }        while(!s.isEmpty()){            int index = s.pop();            m = Math.max(m,s.isEmpty()?dp[index]*dp.length:dp[index]*(dp.length-s.peek()-1));        }        return m;    }}


原创粉丝点击