[Leetcode] Maximal Rectangle

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

Solution:

 1 public class Solution {
 2     public int maximalRectangle(char[][] matrix) {
 3         if (matrix.length == 0||matrix[0].length==0)
 4             return 0;
 5         int row = matrix.length;
 6         int col = matrix[0].length;
 7         int[][] temp = new int[row][col];
 8         for(int i=0;i<col;++i){
 9             temp[0][i]=(matrix[0][i]=='1')?1:0;
10         }
11         for(int i=1;i<row;++i){
12             for(int j=0;j<col;++j){
13                 temp[i][j]=(matrix[i][j]=='1')?(temp[i-1][j]+1):0;
14             }
15         }
16         int maxArea=0;
17         for(int i=row-1;i>=0;--i){
18             int tempArea=getArea(temp[i]);
19             maxArea=Math.max(maxArea, tempArea);
20         }
21         return maxArea;
22     }
23 
24     private int getArea(int[] temp) {
25         // TODO Auto-generated method stub
26         int max=0;
27         for(int position=0;position<temp.length;++position){
28             int tempMax=0;
29             int currentVal=temp[position];
30             tempMax+=currentVal;
31             int left=position-1;
32             int right=position+1;
33             while(left>=0&&temp[left]>=currentVal){
34                 tempMax+=currentVal;
35                 left--;
36             }
37             while(right<temp.length&&temp[right]>=currentVal){
38                 tempMax+=currentVal;
39                 right++;
40             }
41             max=Math.max(max, tempMax);
42         }
43         return max;
44     }
45 }

 

posted @ 2014-11-10 05:54  Phoebe815  阅读(114)  评论(0编辑  收藏  举报