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.
For example, given the following matrix:
1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
Return 6.
我曹,还是单调栈。
记录下以当前行向上能得到的连续的1的个数(比如有sum[i]个),统计以这个sum[i]为最小值,向左,向右能扩展的最大距离。
class Solution { public: class node { public: int x, left, right; }; int solve(int n, int m, vector<int>& sum) { vector<node> v; int ans = 0; for (int i = 0; i < m; ++i) { if (v.empty()) v.push_back({sum[i], i, i}); else { node u = {sum[i], i, i}; while(!v.empty() && sum[i] < v.back().x) { node tmp = v.back(); v.pop_back(); if (!v.empty()) v.back().right = tmp.right; u.left = tmp.left; int y = (tmp.right - tmp.left + 1) * tmp.x; if (y > ans) ans = y; } v.push_back(u); } } while (!v.empty()) { node tmp = v.back(); v.pop_back(); int y = (tmp.right - tmp.left + 1) * tmp.x; ans = max(ans, y); if (!v.empty()) v.back().right = tmp.right; } return ans; } int maximalRectangle(vector<vector<char>>& matrix) { int n = matrix.size(); if (n == 0) return 0; int m = matrix[n-1].size(); vector<int> sum(m); int ans = 0; for (int i = 0; i < m; ++i) sum[i] = (matrix[0][i] - '0'); ans = solve(n, m, sum); for (int i = 1; i < n; ++i) { for (int j = 0; j < m; ++j) { if (matrix[i][j] == '1') sum[j]++; else sum[j] = 0; } ans = max(ans, solve(n, m, sum)); } return ans; } };
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: