leetcode--Maximal Rectangle

水深无声 2021-10-25 12:42 314阅读 0赞

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area.

  1. public class Solution {
  2. public int maximalRectangle(char[][] matrix) {
  3. int row = matrix.length;
  4. if(row == 0) return 0;
  5. int column = matrix[0].length;
  6. int[][] consecutiveOnes = new int[row][column];
  7. for(int i = 0; i < row; ++i) {
  8. for(int j = 0; j < column; ++j){
  9. if(matrix[i][j] - '0' == 1){
  10. if(j == 0)
  11. consecutiveOnes[i][j] = 1;
  12. else
  13. consecutiveOnes[i][j] = consecutiveOnes[i][j - 1] + 1;
  14. }
  15. else
  16. consecutiveOnes[i][j] = 0;
  17. }
  18. }
  19. //calculate the max area. we check each element of consecutiveOnes column by column
  20. int maxArea = 0;
  21. for(int i = 0; i < column; ++i){
  22. for(int j = 0; j < row; ++j){
  23. if(consecutiveOnes[j][i] != 0){
  24. int minWidth = consecutiveOnes[j][i];
  25. int index = j;
  26. while(index >= 0 && consecutiveOnes[index][i] != 0){
  27. minWidth = Math.min(minWidth, consecutiveOnes[index][i]);
  28. maxArea = Math.max(maxArea, minWidth * (j - index + 1));
  29. --index;
  30. }
  31. }
  32. }
  33. }
  34. return maxArea;
  35. }
  36. }

  

Remark: the second part (to seek the max area) can be solved by method used in “largest rectangle histogram” problem. Therefore, there is an algorithm with time O(row * column).

转载于:https://www.cnblogs.com/averillzheng/p/3825713.html

发表评论

表情:
评论列表 (有 0 条评论,314人围观)

还没有评论,来说两句吧...

相关阅读