Maximal Rectangle

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 };

 

posted @ 2014-04-24 03:50  beehard  阅读(170)  评论(0编辑  收藏  举报