码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Maximal Rectangle

时间:2015-09-02 13:14:48      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

This link shares a nice solution with explanation using DP. You will be clear of the algorithm after running it on its suggested example:

matrix = [
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 0]];

The code is rewritten as follows.

 1 class Solution {
 2 public:
 3     int maximalRectangle(vector<vector<char>>& matrix) {
 4         if (matrix.empty()) return 0;
 5         const int m = matrix.size(), n = matrix[0].size();
 6         int *left = new int[n](), *right = new int[n](), *height = new int[n]();
 7         fill_n(right, n, n);
 8         int area = 0;
 9         for (int i = 0; i < m; i++) {
10             int l = 0, r = n;
11             for (int j = 0; j < n; j++)
12                 height[j] += matrix[i][j] == 1 ? 1 : -height[j];
13             for (int j = 0; j < n; j++) {
14                 if (matrix[i][j] == 1) left[j] = max(left[j], l);
15                 else left[j] = 0, l = j + 1;
16             }
17             for (int j = n - 1; j >= 0; j--) {
18                 if (matrix[i][j] == 1) right[j] = min(right[j], r);
19                 else right[j] = n, r = j;
20             }
21             for (int j = 0; j < n; j++)
22                 area = max(area, (right[j] - left[j]) * height[j]);
23         }
24         return area;
25     }
26 };

 

[LeetCode] Maximal Rectangle

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4778231.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!