# 19.2.23 [LeetCode 85] Maximal Rectangle

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

Example:

Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6

## 题解

 1 class Solution {
2 public:
3     int maximalRectangle(vector<vector<char>>& matrix) {
4         if (matrix.empty())return 0;
5         int m = matrix.size(), n = matrix[0].size(), ans = 0;
6         vector<int>height(n, 0),left(n, 0), right(n, n);
7         for (int i = 0; i < m; i++) {
8             int s = 0;
9             for (int j = 0; j < n; j++) {
10                 if (matrix[i][j] == '0') {
11                     height[j] = 0;
12                     left[j] = 0;
13                     s = j + 1;
14                 }
15                 else {
16                     left[j] = max(left[j], s);
17                     height[j]++;
18                 }
19             }
20             int e = n - 1;
21             for (int j = n - 1; j >= 0; j--) {
22                 if (matrix[i][j] == '0') {
23                     right[j] = n;
24                     e = j - 1;
25                 }
26                 else {
27                     right[j] = min(right[j], e);
28                 }
29             }
30             for (int j = 0; j < n; j++)
31                 if (matrix[i][j] == '1')
32                     ans = max(ans, (right[j] - left[j] + 1)*height[j]);
33         }
34         return ans;
35     }
36 };
View Code

posted @ 2019-02-23 09:20  TobicYAL  阅读(155)  评论(0编辑  收藏  举报