leetCode 85. Maximal Rectangle

本文介绍了两种高效的方法来解决寻找二维二进制矩阵中最大的全1矩形的问题。第一种方法通过遍历矩阵的所有可能子矩阵来计算其面积;第二种方法则通过构建直方图并利用已有的最大矩形面积算法来简化计算过程。

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.

找到矩阵中的最大全1矩阵

第一种方法,先从matrix[0][0]开始作为起始点start,然后从stasrt左至右、上至下遍历,matrix[i][j]作为end,计算每个矩阵面积。对于每一行,只要该行任意end不能构成全1矩阵,则该行end右边的点都不能构成全1矩阵,不需要遍历。

public static int maximalRectangle(char[][] matrix) {
         if(matrix == null ||matrix.length<1)return 0;
         int row = matrix.length;
         int col = matrix[0].length;
         int max=0;
         for(int i=0;i<row;i++){
             for(int j=0;j<col;j++){
                 for(int k=i;k<row;k++){
                     for(int y=j;y<col;y++){
                         int temp=area(i,j,k,y,matrix);
                        if(temp<0){
                            break;
                        }
                        else
                            max=max>temp?max:temp;
                     } 
                 }
             } 
         }


        return max;

        }



     public static int area(int x1,int y1,int x2,int y2,char[][] matrix){
         for(int i=x1;i<=x2;i++){
             for(int j=y1;j<=y2;j++){
                 if(matrix[i][j]=='0')
                     return -1;
             }
         }
         return (x2-x1+1)*(y2-y1+1);
     }

第二种方法,借用84直方图求最大矩阵方法,对于矩阵每一层,往上构成直方图,比如第三层,就构成一个1,1,2,2,2的直方图,那么最大面积就为6,对每一层调用直方图面积即可求出最大值

 public static int maximalRectangle(char[][] matrix) {
         if(matrix == null ||matrix.length<1)return 0;
         int row = matrix.length;
         int col = matrix[0].length;
         int max=0;
         for(int i=0;i<row;i++){
             int A[] = new int[col];

             for(int j=0;j<col;j++){
                 int k=i;
                 int temp=0;
                while(k>=0){
                    if(matrix[k][j]=='1'){
                        temp++;
                    }
                    else
                        break;
                    k--;
                }
                A[j]=temp;

             }
             int temp = largestRectangleArea(A);
             if(temp>max)
                 max=temp;
         }


        return max;

        }

     public static int largestRectangleArea(int[] heights) {
         if(heights==null||heights.length<1)return 0;

         int n=heights.length;
         if(n==1)return heights[0];
         int max=0;
         Stack<Integer> st = new Stack<Integer>();
         st.push(heights[0]);
         int i=1;
         while(i<n){
             if(heights[i]>=st.peek()){
                 st.push(heights[i]);
             }
             else{
                 int count1=1;
                 while(!st.isEmpty()&&st.peek()>heights[i]){
                     int temp=st.pop();
                     if(count1*temp>max){
                         max=count1*temp;
                     }
                     count1++;
                 }
                 while(count1-->0){
                     st.push(heights[i]);
                 }
             }

             i++;
         }
         int count1=1;
         while(!st.isEmpty()){
             int temp=st.pop();
             if(count1*temp>max){
                 max=count1*temp;
             }
             count1++;
         }
         return max;
        }
LeetCode85 题的题目名称是: ## **Maximal Rectangle**(最大矩形) --- ### 🔹题目描述: 给定一个只包含 `0` 和 `1` 的二维二进制矩阵 `matrix`,找出只包含 `1` 的最大矩形,并返回其面积。 --- ### 🔹示例: ```text 输入: [ ["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"] ] 输出: 6 ``` 解释: 最大矩形是由第二行和第三行中的 `1` 构成的,大小为 `2 x 3 = 6`。 --- ### 🔹解法思路: 这道题是 **LeetCode 84(Largest Rectangle in Histogram)** 的二维扩展。 我们可以将每一行看作是直方图的底部,并逐行构建“高度数组”,然后对每一行使用 LeetCode 84 的单调栈解法来计算当前行所能构成的最大矩形面积。 --- ### 🔹C++ 实现代码: ```cpp #include <iostream> #include <vector> #include <stack> using namespace std; // LeetCode 84 的函数:直方图中最大矩形面积 int largestRectangleArea(vector<int>& heights) { stack<int> s; int maxArea = 0; heights.push_back(0); // 添加一个0,确保最后所有元素都被弹出 for (int i = 0; i < heights.size(); ++i) { while (!s.empty() && heights[i] < heights[s.top()]) { int height = heights[s.top()]; s.pop(); int width = s.empty() ? i : i - s.top() - 1; maxArea = max(maxArea, height * width); } s.push(i); } heights.pop_back(); // 恢复原数组 return maxArea; } // LeetCode 85 主函数 int maximalRectangle(vector<vector<char>>& matrix) { if (matrix.empty() || matrix[0].empty()) return 0; int rows = matrix.size(); int cols = matrix[0].size(); vector<int> heights(cols, 0); // 每列的高度 int maxArea = 0; for (int row = 0; row < rows; ++row) { // 更新高度数组 for (int col = 0; col < cols; ++col) { if (matrix[row][col] == '1') { heights[col] += 1; } else { heights[col] = 0; } } // 使用 LeetCode 84 的方法计算当前行的最大面积 maxArea = max(maxArea, largestRectangleArea(heights)); } return maxArea; } // 主函数测试 int main() { vector<vector<char>> matrix = { {'1','0','1','0','0'}, {'1','0','1','1','1'}, {'1','1','1','1','1'}, {'1','0','0','1','0'} }; cout << "最大矩形面积是: " << maximalRectangle(matrix) << endl; return 0; } ``` --- ### 🔹代码解释: - `largestRectangleArea`:使用单调栈实现 LeetCode 84 的解法。 - `maximalRectangle`: - 遍历每一行,维护一个 `heights` 数组,表示当前行以上每列的“高度”。 - 每一行都调用一次 `largestRectangleArea` 来计算最大矩形面积。 - 时间复杂度:`O(rows * cols)`,因为每一行构建高度数组是 `O(cols)`,而单调栈也是 `O(cols)`。 --- ### 🔹总结: | 项目 | 内容 | |------|------| | 难度 | 困难 | | 算法 | 单调栈 + 动态规划 | | 时间复杂度 | O(rows × cols) | | 空间复杂度 | O(cols) | | 相关题号 | LeetCode 84, 221(最大正方形) | --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值