Maximal Rectangle

本文介绍了一种求解二维二进制矩阵中全由1构成的最大矩形面积的方法。通过动态规划记录每个元素左侧和上方连续1的数量,并计算包含该元素在内的矩形面积,最终得到最大面积。

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

Solution: 1. dp. (72 milli secs for the large).
a) dp[i][j] records the number of consecutive '1' on the left and up of the element matrix[i][j].
b) For each element(i,j), calculate the area of rectangle including the element itself.
2. calculate 'Largest Rectangle in Histogram' for each row.
Note... understanding

 1 class Solution {
 2 public:
 3     int maximalRectangle(vector<vector<char> > &matrix) {
 4         if (matrix.empty() || matrix[0].empty()) return 0;
 5         int N = matrix.size(), M = matrix[0].size();
 6         pair<int, int> dp[N][M];
 7         memset(dp, 0, sizeof(dp));
 8         int res = 0;
 9         for (int i = 0; i < N; ++i)
10         {
11             for (int j = 0; j < M; ++j)
12             {
13                 if (matrix[i][j] == '0')
14                     continue;
15                 
16                 int x = (j == 0) ? 1 : dp[i][j-1].first + 1;
17                 int y = (i == 0) ? 1 : dp[i-1][j].second + 1;
18                 dp[i][j] = make_pair(x, y);
19                 
20                 int minHeight = y;
21                 for (int k = j; k > j - x; --k)
22                 {
23                     minHeight = min(minHeight, dp[i][k].second);
24                     res = max(res, minHeight * (j - k + 1));
25                 }
26             }
27         }
28         return res;
29     }
30 };

 

转载于:https://www.cnblogs.com/zhengjiankang/p/3682129.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值