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

leetcode 85. Maximal Rectangle

时间:2017-10-09 23:56:44      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:nbsp   bsp   lan   ini   logs   blank   color   ems   rip   

link

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

标签:nbsp   bsp   lan   ini   logs   blank   color   ems   rip   

原文地址:http://www.cnblogs.com/bbbbbq/p/7643397.html

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