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.

 1 public class Solution {
 2     public int maximalRectangle(char[][] matrix) {
 3         int row = matrix.length;
 4         if(row<=0) return 0;
 5         int col = matrix[0].length;
 6         int left [] = new int[col];
 7         int right[] = new int [col];
 8         int height[] = new int[col];
 9         int area =0;
10         for(int i=0;i<col;i++){
11             right[i] = col;
12         }
13         for(int i=0;i<row;i++){
14             int L = 0;int R=col;
15             for(int j=0;j<col;j++){
16                 if(matrix[i][j]=='1'){
17                     height[j]++;
18                     left[j] = Math.max(left[j],L);
19                 }
20                 else{
21                     height[j]=0;
22                     left[j]=0;
23                     L=j+1;
24                     right[j] =col;
25                 }
26             }
27             for(int j=col-1;j>=0;j--){
28                 if(matrix[i][j]=='1'){
29                     right[j] = Math.min(right[j],R);
30                     area = Math.max(area,(right[j]-left[j])*height[j]);
31                 }
32                 else{
33                     R = j;
34                 }
35             }
36         }
37         return area;
38     }
39 }
View Code

 

posted @ 2014-02-06 14:47  krunning  阅读(135)  评论(0编辑  收藏  举报