LeetCode: Maximal Rectangle

Maximum size square sub-matrix with all 1s

http://www.geeksforgeeks.org/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix/

 

 1 public static int maximalRectangle(char[][] matrix) {
 2         int max = 0;
 3         int row = matrix.length; 
 4         int col = matrix[0].length;
 5         int[][] height = new int[row][col];
 6         for (int j = 0; j<col; j++) {
 7             height[0][j] = matrix[0][j]-'0';
 8         }
 9         for (int i=1; i<row; i++) {
10             for (int j=0; j<col; j++) {
11                 if (matrix[i][j] == '1') {
12                     height[i][j] = height[i-1][j]+1;
13                 }
14             }
15         }
16         
17         for (int i=0; i<row; i++) {
18             int area = largestRectangleArea(height[i]);
19             if (area > max) max = area;
20         }
21         
22         return max;
23     }
24     
25     public static int largestRectangleArea(int[] height) {
26         Stack<Integer> stack = new Stack<Integer>();
27         int i = 0;
28         int maxArea = 0;
29         int[] h = new int[height.length + 1];
30         h = Arrays.copyOf(height, height.length + 1);
31         while(i < h.length){
32             if(stack.isEmpty() || h[stack.peek()] <= h[i]){
33                 stack.push(i++);
34             }else {
35                 int t = stack.pop();
36                 maxArea = Math.max(maxArea, h[t] * (stack.isEmpty() ? i : i - stack.peek() - 1));
37             }
38         }
39         return maxArea;
40      }

http://www.cnblogs.com/lichen782/p/3196570.html

另外一种方法:

http://www.cnblogs.com/Rosanna/p/3527808.html

 

posted on 2014-04-18 11:39  longhorn  阅读(179)  评论(0编辑  收藏  举报

导航