leetcode 85. Maximal Rectangle
Posted =w=
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
题意:求出01矩阵中由1组成的最大的矩形面积。
思路:
哈哈,上一题的扩展版本。
对每个位置算出其往下几行连续的1的数量。然后就变成了上一题~
code:
class Solution { public: int maximalRectangle(vector<vector<char>>& matrix) { if(matrix.size() == 0 || matrix[0].size() == 0) return 0; int n = matrix.size(), m = matrix[0].size(); vector<vector<int>> state(n , vector<int>(m, 0)); for(int i = 0; i < m; i++){ state[n-1][i] = (matrix[n-1][i] == ‘1‘); } for(int i = n - 2; i >= 0; i --){ for(int j = 0; j < m; j++){ if(matrix[i][j] == ‘0‘) state[i][j] = 0; else{ state[i][j] = state[i+1][j] + 1; } } } int ans = 0; for(int i = 0; i < n; i++){ stack<int>s; vector<int>leftPos(m); for(int j = 0; j < m; j++){ while(!s.empty() && state[i][s.top()] >= state[i][j]) s.pop(); if(s.empty()) leftPos[j] = 0; else{ leftPos[j] = s.top() + 1; } s.push(j); } while(!s.empty()) s.pop(); for(int j = m - 1; j >= 0; j--){ while(!s.empty() && state[i][s.top()] >= state[i][j] ) s.pop(); int rightPos = m - 1; if(!s.empty()) rightPos = s.top() - 1; int tmp = (rightPos - leftPos[j] + 1) * state[i][j]; ans = max(ans, tmp); s.push(j); } } return ans; } };
以上是关于leetcode 85. Maximal Rectangle的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 85. Maximal Rectangle
Leetcode 85. Maximal Rectangle
LeetCode 85: Maximal Recetangle
LeetCode(85) Maximal Rectangle