首页 > 其他 > 详细

85. Maximal Rectangle

时间:2016-09-18 21:59:18      阅读:103      评论:0      收藏:0      [点我收藏+]

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 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Return 6.


【题目分析】


【思路】

【java代码】

 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         if(col == 0) return 0;
 7         
 8         int maxArea = 0;
 9         
10         for(int i = 0; i < row; i++){
11             int[] height = new int[col];
12             for(int j = 0; j < col; j++){
13                 if(matrix[i][j] == ‘1‘){
14                     for(int k = i; k >=0; k--){
15                         if(matrix[k][j] == ‘1‘){
16                             height[j]++;
17                         }
18                         else break;
19                     }
20                 }
21             }
22             maxArea = Math.max(maxArea, largestRectangleArea(height));
23         }
24         
25         return maxArea;
26     }
27     
28     public int largestRectangleArea(int[] height) {
29         int len = height.length;
30         Stack<Integer> s = new Stack<Integer>();
31         int maxArea = 0;
32         for(int i = 0; i <= len; i++){
33             int h = (i == len ? 0 : height[i]);
34             if(s.isEmpty() || h >= height[s.peek()]){
35                 s.push(i);
36             }else{
37                 int tp = s.pop();
38                 maxArea = Math.max(maxArea, height[tp] * (s.isEmpty() ? i : i - 1 - s.peek()));
39                 i--;
40             }
41         }
42         return maxArea;
43     }
44 }

 

85. Maximal Rectangle

原文:http://www.cnblogs.com/liujinhong/p/5883193.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!