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.
Show Tags
Have you met this question in a real interview? Yes No
Discuss
SOLUTION 1:
1 public class Solution { 2 public int maximalRectangle(char[][] matrix) { 3 if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { 4 return 0; 5 } 6 7 int rows = matrix.length; 8 int cols = matrix[0].length; 9 10 int[][] h = new int[rows][cols]; 11 12 int max = 0; 13 14 for (int i = 0; i < rows; i++) { 15 for (int j = 0; j < cols; j++) { 16 17 h[i][j] = matrix[i][j] == '1' ? 1: 0; 18 19 if (i != 0 && h[i][j] != 0) { 20 h[i][j] = h[i - 1][j] + 1; 21 } 22 23 if (j == cols - 1) { 24 max = Math.max(max, maxArea(h[i])); 25 } 26 } 27 } 28 29 return max; 30 } 31 32 public int maxArea(int[] h) { 33 Stack<Integer> s = new Stack<Integer>(); 34 35 int max = 0; 36 int i = 0; 37 38 // 注意,这里使用<= 因为当i到达最后,需要计算一次。 39 while (i <= h.length) { 40 // 41 if (s.isEmpty() || i < h.length && h[i] >= h[s.peek()]) { 42 s.push(i); 43 i++; 44 } else { 45 int height = h[s.pop()]; 46 int width = s.isEmpty() ? i: i - s.peek() - 1; 47 max = Math.max(max, height * width); 48 } 49 } 50 51 return max; 52 } 53 }
2015.1.3 redo:
1 public class Solution { 2 public int maximalRectangle(char[][] matrix) { 3 if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { 4 return 0; 5 } 6 7 int rows = matrix.length; 8 int cols = matrix[0].length; 9 int[][] h = new int[matrix.length][matrix[0].length]; 10 11 int maxArea = 0; 12 13 for (int i = 0; i < rows; i++) { 14 for (int j = 0; j < cols; j++) { 15 if (matrix[i][j] == '0') { 16 h[i][j] = 0; 17 } else { 18 if (i == 0) { 19 h[i][j] = 1; 20 } else { 21 h[i][j] = 1 + h[i - 1][j]; 22 } 23 } 24 25 if (j == cols - 1) { 26 // the last element of every row. 27 int maxRec = maxAreaInRow(h[i]); 28 maxArea = Math.max(maxArea, maxRec); 29 } 30 } 31 } 32 33 return maxArea; 34 } 35 36 public int maxAreaInRow(int[] h) { 37 Stack<Integer> s = new Stack<Integer>(); 38 39 int i = 0; 40 int max = 0; 41 while (i <= h.length) { 42 // the current height is higher or equal than the one in the stack. 43 if (s.isEmpty() || i < h.length && h[i] >= h[s.peek()]) { 44 s.push(i); 45 i++; 46 } else { 47 // get the area. 48 int hight = h[s.pop()]; 49 int w = s.isEmpty() ? i: i - s.peek() - 1; 50 max = Math.max(max, hight * w); 51 } 52 } 53 54 return max; 55 } 56 }