码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Maximal Rectangle

时间:2014-11-10 06:32:28      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   sp   for   div   

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 }

 

[Leetcode] Maximal Rectangle

标签:style   blog   io   color   ar   os   sp   for   div   

原文地址:http://www.cnblogs.com/Phoebe815/p/4086304.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!