標籤:style blog http color io 2014 for re
Given a 2D binary matrix filled with 0‘s and 1‘s, find the largest rectangle containing all ones and return its area.
題解,很巧妙的一道題,對於一個0-1矩陣,它的每一行及以上都可以看作一個長條圖(如所示),利用Largest Rectangle in Histogram的方法,可以在O(n)的時間搜尋出這一行及以上的長條圖中面積最大的矩形,對矩陣的每一行依次做這個操作,就可以在O(n2)的時間搜尋出最大的矩形了。
將原矩陣轉換成長條圖矩陣的方法:設用transfer矩陣存放轉換後的長條圖,則
transfer[0][j] = matrix[0][j] - ‘0‘;transfer[i][j] = (matrix[i][j] == ‘0‘ ? 0: transfer[i-1][j] + 1); (i >= 1)
代碼如下:
1 public class Solution { 2 public int largestRectangleArea(int[] height) { 3 if(height == null || height.length == 0) 4 return 0; 5 Stack<Integer> index = new Stack<Integer>(); 6 int totalMax = 0; 7 ArrayList<Integer> newHeight = new ArrayList<Integer>(); 8 for(int i:height) newHeight.add(i); 9 newHeight.add(0);10 11 12 for(int i = 0;i < newHeight.size();i++){13 if(index.isEmpty() || newHeight.get(i) >= newHeight.get(index.peek()))14 index.push(i);15 else{16 int top = index.pop();17 totalMax = Math.max(totalMax,newHeight.get(top) * (index.isEmpty()?i:i-index.peek()-1));18 i--;19 }20 }21 22 return totalMax;23 }24 public int maximalRectangle(char[][] matrix) {25 if(matrix == null || matrix.length == 0)26 return 0;27 int m = matrix.length;28 int n = matrix[0].length;29 int totalMax = 0;30 int[][] transfer = new int[m][n];31 32 //transform matrix to histogram in a new matrix33 for(int i = 0;i < n;i++)34 transfer[0][i] = matrix[0][i]- ‘0‘;35 for(int i = 1;i < m;i++){36 for(int j = 0;j < n;j++){37 if(matrix[i][j] == ‘0‘ )38 transfer[i][j] = 0;39 else {40 transfer[i][j] = transfer[i-1][j] + 1; 41 }42 }43 }44 45 //Using histogram to find the biggest rectangle46 for(int i = 0;i < m;i++){47 totalMax = Math.max(totalMax, largestRectangleArea(transfer[i]));48 }49 50 return totalMax;51 }52 }