LeetCode OJ 之 Maximal Rectangle (最大的矩形)

36 篇文章 0 订阅
24 篇文章 0 订阅

题目:

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,找出只包含1的最大矩形并且返回这个矩形的面积。

思路:

本题通过下图变换可以转换为求 :LeetCode OJ 之 Largest Rectangle in Histogram (直方图中的最大矩形) 。


转换后矩阵可以变成下图所示矩阵,求最大矩阵相当于对每一行求直方图的最大矩形面积。


代码:

[cpp]  view plain  copy
  1. class Solution {  
  2. public:  
  3.     int maximalRectangle(vector<vector<char> > &matrix)   
  4.     {  
  5.         int result = 0;  
  6.         if(matrix.empty() || matrix[0].empty())  
  7.             return result;  
  8.         int row = matrix.size();  
  9.         int col = matrix[0].size();  
  10.         vector<vector<int> > histogram(row , vector<int>(col,0));//直方图矩阵  
  11.         for(int i = 0 ; i < row ; i++)  
  12.         {  
  13.             for(int j = 0 ; j < col ; j++)  
  14.             {  
  15.                 if(i == 0)  //第一行  
  16.                     histogram[i][j] = (matrix[i][j] == '1' ? 1 : 0);  
  17.                 else  
  18.                     histogram[i][j] = (matrix[i][j] == '1' ? histogram[i-1][j] + 1 : 0);//注意下一行不是等于上一行+当前行  
  19.             }  
  20.         }  
  21.         //对每一行调用largestRectangleArea求最大矩形  
  22.         for(int i = 0 ; i < row ; i++)  
  23.         {  
  24.             int tmp = largestRectangleArea(histogram[i]);  
  25.             result = max(result , tmp);  
  26.         }  
  27.         return result;  
  28.     }  
  29.     int largestRectangleArea(vector<int> &height)   
  30.     {  
  31.         stack<int> stk;  
  32.         height.push_back(0);  
  33.         int maxArea = 0 ;  
  34.         for(int i = 0 ; i < height.size() ;)  
  35.         {  
  36.             if(stk.empty() || height[i] > height[stk.top()])  
  37.             {  
  38.                 stk.push(i);  
  39.                 i++;  
  40.             }  
  41.             else  
  42.             {  
  43.                 int index = stk.top();  
  44.                 stk.pop();  
  45.                 int tmp = height[index] * (stk.empty() ? i : i-stk.top()-1);  
  46.                 maxArea = max(maxArea , tmp);  
  47.             }  
  48.         }  
  49.         return maxArea;  
  50.     }  
  51. };  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值